Skip to content
Advertisement

Show padding zeros using DecimalFormat

I’m using DecimalFormat to format doubles to 2 decimal places like this:

JavaScript

It works, but if i have a number like 20, it gives me this:

JavaScript

and I want this:

JavaScript

Any suggestions?

Advertisement

Answer

The DecimalFormat class is for transforming a decimal numeric value into a String. In your example, you are taking the String that comes from the format( ) method and putting it back into a double variable. If you are then outputting that double variable you would not see the formatted string. See the code example below and its output:

JavaScript

Which outputs:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement