Today, stepping on a hole, using DecimalFormat to complete rounding, but the float type is passed in, several rounds of testing only to find a problem, the incoming float will be converted to double type, we all know that float is 4 bits, double is 8 bits, A strong turn is sure to cause progress loss.
Use the following method
publicstaticformatMoney(floatvalue) { new DecimalFormat("####.#"); format.setRoundingMode(RoundingMode.HALF_UP); return"¥" + format.format(value); }
- Incoming 1.15 returns 1.1.
Incoming 1.25 returns 1.3.
Oh, that's weird. Format.format (value) receives the double type by default, I have now passed the float type, and there is no error, but it has been strongly turned to double type, 1.15 has been converted to 1.149999999 ... precision has been lost.
The solution uses BigDecimal to not lose progress by converting the float to a bit double
Modify method
publicstaticfloatformatFloat(floatvalue) { decimalnew BigDecimal(String.valueOf(value)); new DecimalFormat("####.#"); format.setRoundingMode(RoundingMode.HALF_UP); return Float.parseFloat(format.format(decimal.doubleValue())); }
Use Format.setroundingmode (ROUNDINGMODE.HALF_UP), you can control the way the conversion, specific documents can refer to the Java doc
DecimalFormat rounding float type of pit