randomuser1
randomuser1

Reputation: 2803

why does my DecimalFormat not work for 2 decimal places in Java?

I have a DecimalFormat in java and when I use it, it does not work as expected. In the input I'm getting 150000, and I want to have the 15.00 as an outcome. The code looks as follows:

import java.text.DecimalFormat;

public class MyClass {
    public static void main(String args[]) {
      long x=150000;
      DecimalFormat df = new DecimalFormat("#.##");
      System.out.println("x " + x/10000);
      long y = x/10000;
      
      System.out.println(df.format(y));
    }
}

and still, the console shows 15 instead of 15.00. What am I missing here? Btw, is there any better way to make such formatter (while trying to convert 15000 to 15.00)? Or is the best option to just divide it by 10000 in that case? Thank you for any feedback!

Upvotes: 2

Views: 1011

Answers (1)

Vsevolod Golovanov
Vsevolod Golovanov

Reputation: 4206

Your pattern should be:

DecimalFormat df = new DecimalFormat("#.00");

Because as DecimalFormat's javadoc says:

Symbol Location Localized? Meaning
0 Number Yes Digit
# Number Yes Digit, zero shows as absent

Btw, is there any better way to make such formatter (while trying to convert 15000 to 15.00)? Or is the best option to just divide it by 10000 in that case?

Formatting is just representing a value in a certain text form. It's not about changing a value, and 15000 and 15 are different values. So dividing like that is a proper way to get a different value.

Upvotes: 3

Related Questions