For example I have the variable 3.545555555, which I would want to truncate to just 3.54.
format("%. 2f", height)); This will trim the double value 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).
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.
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 %.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With