-1

I have a situation where I need to dynamically mask my decimals up to 2 decimal places. The user can only type in whole numbers. Examples:

  1. If the user types in 5, the output will be .05
  2. If the user types in 57, the output will be .57
  3. If the user types in 157, the output will be 1.57

How can I achieve this? I was not able to find a masking format that would allow this, so do I need to write my own? If so, any tips?

Here's what I have so far:

import java.text.DecimalFormat;

public class MyClass {
    public static void main(String args[]) {
        DecimalFormat myFormat = new DecimalFormat(".##");
        System.out.println(myFormat.format(5)); // Expecting .05
        System.out.println(myFormat.format(57)); // Expecting .57
        System.out.println(myFormat.format(157)); // Expecting 1.57
    }
}
Tim
  • 478
  • 4
  • 15
  • 2
    This isn't a problem of "masking". You need to call `format(5 / 100.0)`, for example. In other words, you can only format an actual floating point number, not an integer – OneCricketeer Dec 19 '22 at 19:53
  • @Progman the user can only input whole numbers. So to get 5.01, the user would input 501. – Tim Dec 19 '22 at 19:59
  • @Progman Oh crap, sorry. Fixed it in the edits. – Tim Dec 19 '22 at 20:02

1 Answers1

1

DecimalFormat is for formatting a number that already has the right value, not for unusual entry methods.

You probably will have to perform a manual conversion between the entered string and a number to output. Then you can use that class to do the right output

To skip the leading zero before the comma you need to specify this format: new DecimalFormat("#.00")

cyberbrain
  • 3,433
  • 1
  • 12
  • 22