I want to truncate a float value in Java.
Following are my requirements:
- if i have 12.49688f, it should be printed as 12.49 without rounding off
- if it is 12.456 in double, it should be printed as 12.45 without rounding off
- In any case if the value is like 12.0, it should be printed as 12 only.
Condition 3 is to be always kept in mind.It should be concurrent with
truncating logic.
P.S: I am using Java 1.5 . So i know how to do it in Java 1.6 i.e using Decimal Format and calling setroundingMode () Method.
I need to know for Java 1.5
Multiply, use Math#floor and divide before providing the number to the DecimalFormat. This is the same as cutoff roundig.
This isn’t perfect because of rounding errors in floating point calculation, so you will still have to specify N decimals to the DecimalFormat.
A (more expensive, but also more logical) alternative is to use a BigDecimal.