Reputation: 474
I'm trying to make a double to be this format 00,00
Example
9,21341 > 09,21
10,4312 > 10,43
1,01233 > 01,01
42,543 > 42,54
Currently I'm using the String.Format to round the double
String.format("%s %02.2f - ", example.getName(), example.getDouble());
This does not add the extra zero in front of the double if it is smaller than 10.
Upvotes: 1
Views: 3764
Reputation: 26142
Formatter class (which is the basis of String.format
method) operates using the concept of "fields". That is, each field is of some specific size and can be padded. In your case, you could use a formating like %05.2f
, which would mean a field of size 5, with 2 symbols after the point padded with zeroes to the left.
However, if you need some fine-grained formatting of numbers usually what you are looking for is DecimalFormat class, which allows you to easily customize how the numbers are represented.
Example (ideone link):
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
DecimalFormat decimalFormat = new DecimalFormat("#00.00");
System.out.println(decimalFormat.format(0.99f));
System.out.println(decimalFormat.format(9.99f));
System.out.println(decimalFormat.format(19.99f));
System.out.println(decimalFormat.format(119.99f));
}
}
Output:
00.99
09.99
19.99
119.99
Upvotes: 7