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.
// Replace N with the desired number of decimals after the comma
number = Math.floor(1eN * number) / 1eN
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.
// Given as seperate statements for clarity, but these can be combined into a single line
// Replace "N" with the number of decimals after the comma
MathContext NDecimals = new MathContext(N, RoundingMode.FLOOR);
BigDecimal bdNumber = new BigDecimal(number, NDecimals);
number = bdNumber.doubleValue();