Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I truncate a double to only two decimal places in Java?

For example I have the variable 3.545555555, which I would want to truncate to just 3.54.

like image 740
Johnny Avatar asked Oct 12 '11 22:10

Johnny


People also ask

How do you trim a double in Java?

format("%. 2f", height)); This will trim the double value to two decimal places.

How do you truncate to two decimal places?

To truncate a number to 2 decimal places, miss off all the digits after the second decimal place. To truncate a number to 3 significant figures, miss off all the digits after the first 3 significant figures (the first non-zero digit and the next two digits).

How do I limit decimal places in Java?

Using the format() method "%. 2f" denotes 2 decimal places, "%. 3f" denotes 3 decimal places, and so on. Hence in the format argument, we can mention the limit of the decimal places.

How do you write to 2 decimal places in Java?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


1 Answers

If you want that for display purposes, use java.text.DecimalFormat:

 new DecimalFormat("#.##").format(dblVar); 

If you need it for calculations, use java.lang.Math:

 Math.floor(value * 100) / 100; 
like image 90
Bozho Avatar answered Sep 21 '22 00:09

Bozho