Solved How do i force make a number double digit

Discussion in 'Spigot Plugin Development' started by Yoreni, Apr 26, 2017.

  1. Iam trying to make a number always be double digits
    so
    3 -> 03
    9 -> 09
    16 -> 16
    Here is my code
    Code (Text):

            if (command.getName().equalsIgnoreCase("wow"))
            {
                int sample = (int) Double.parseDouble(args[0]);
                if(sample < 10);
                {
                    player.sendMessage("Yes");
                    sample = (int)Double.parseDouble("0" + sample);
                }
                player.sendMessage(sample + "");
                return true;
            }
     
    There is no error in consle
     
  2. You can use String#format. Example:
    Code (Text):
    String doubleDigit String.format("%02.0f", myNumber)
    Or NumberFormat:
    Code (Text):
    NumberFormat formatter = new DecimalFormat("00");
    String doubleDigit = formatter.format(5); // ----> 05
     
    • Like Like x 2
  3. NathanWolf

    Supporter

    You can use a number formatter like this:

    Code (Text):
    NumberFormat formatter = new DecimalFormat("00");  
    Best to only create that once (static is OK) and re-use it each time. formatter.format(number) will make a string with two digits.

    EDIT: Sniped! :)
     
    • Like Like x 2
  4. 03 is not an actual number that your computer cares about, if you want it to have a zero appended to it you'll need to convert it to a string. Double means double precision like.
    3.03

    Try this;
    String output = number
    If(number <= 9)
    Output = "0" + number

    System.out.println("number to string number was : " + output);

    This will write the converted number to the console as a string. If it's less than 10 it will get a zero added to it.

    Note once you do this you will be unable to add or subtract to it but as long as you're sending it to the players or scoreboard or something it will be fine.

    To change it back into an integer you would need to do Integer.parseInt(output);
    Then it will again be a usable number but will be missing its leading zero


    Sent from my iPhone using Tapatalk
     
    • Like Like x 1
  5. Pretty sure they want it as a String.
    Better and more convenient methods are already provided above :)
     
    • Like Like x 1
  6. Thank you dNiyn for helping me thank you to others for tring
     
    • Friendly Friendly x 1
  7. Eh idk about that. Numberformatter creates a new instance of whatever format you're using then requires a second string variable.

    String.format might be as good but output = "0"+number
    Is just as good imo.


    Sent from my iPhone using Tapatalk
     
    • Agree Agree x 1
  8. I already tried number formatter and i couldnt get it to work
     
  9. WAS

    WAS

    As far as speed and possibly piling up of these executions I would used dNiym's example