Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed decimal numbers with JAVA

Tags:

java

numbers

How do I represent numbers in the format

001 = 1
002 = 2
003 = 3
010 = 10
020 = 20

The number of digits is always 3.

like image 649
Dave Avatar asked Dec 07 '10 13:12

Dave


People also ask

How do I fix the number of decimal places in Java?

We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places. For DecimalFormat , the default rounding mode is RoundingMode. HALF_EVEN , and we can use setRoundingMode(RoundingMode) to set a specified rounding mode.

How do you fix two decimal places in Java?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

What is .2f in Java?

The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).


2 Answers

If you want to output integers such that they always have leading zeros, use String.format with a zero before the number of digits in the format string, for example:

int i = 3;
String s = String.format("%03d", i);
System.out.println(s);

Gives the output:

003
like image 176
John Pickup Avatar answered Sep 28 '22 09:09

John Pickup


Integer.valueOf("020") is sufficient for your purpose. It will give you 20 as a result. After that you can use it as Integer, int or String.

like image 34
Vladimir Ivanov Avatar answered Sep 28 '22 11:09

Vladimir Ivanov