# 格式浮点数n个小数位

``public static float Redondear(float pNumero, int pCantidadDecimales) { // the function is call with the values Redondear(625.3f, 2) BigDecimal value = new BigDecimal(pNumero); value = value.setScale(pCantidadDecimales, RoundingMode.HALF_EVEN); // here the value is correct (625.30) return value.floatValue(); // but here the values is 625.3 }` `

`String.format("%.2f", floatValue);`

` `BigDecimal roundfinalPrice = new BigDecimal(5652.25622f).setScale(2,BigDecimal.ROUND_HALF_UP);` `

` `NumberFormat formatter = NumberFormat.getInstance(Locale.US); formatter.setMaximumFractionDigits(2); formatter.setMinimumFractionDigits(2); formatter.setRoundingMode(RoundingMode.HALF_UP); Float formatedFloat = new Float(formatter.format(floatValue));` `

` `double roundToDecimalPlaces(double value, int decimalPlaces) { double shift = Math.pow(10,decimalPlaces); return Math.round(value*shift)/shift; }` `

IEEE浮点实现将做半舍入，但他们做二进制半舍入，而不是小数半舍入。 所以你可能没问题

` `float f = 12.345f; DecimalFormat df = new DecimalFormat("#.00"); System.out.println(df.format(f));` `

` `return value.toString();` `

` `value.floatValue();` `

` `public static double roundToDouble(float d, int decimalPlace) { BigDecimal bd = new BigDecimal(Float.toString(d)); bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP); return bd.doubleValue(); }` `

` `public static float roundFloat(float F, int roundTo){ String num = "#########."; for (int count = 0; count < roundTo; count++){ num += "0"; } DecimalFormat df = new DecimalFormat(num); df.setRoundingMode(RoundingMode.HALF_UP); String S = df.format(F); F = Float.parseFloat(S); return F; }` `