Java 将double/float精确到2位小数点
时间:2020-02-23 14:35:10 来源:igfitidea点击:
在本教程中,我们将看到如何在Java中转到2个小数点。
有很多方法:
使用Math.Round(Double * 100.0)/100.0
package org.igi.theitroad;
public class MathRoundMain {
public static void main(String[] args) {
double d=2343.5476;
double roundedDouble = Math.round(d * 100.0)/100.0;
System.out.println("Rounded double: "+roundedDouble);
float f=2343.5476f;
float roundedFloat = (float)Math.round(f * 100.0)/100.0;
System.out.println("Rounded float: "+roundedFloat);
}
}
你必须想知道这是如何工作的。
Double * 100.0 - 234354.76 Math.round(双* 100.0) - 234355.00(圆形到最近值)Math.Round(Double * 100.0)/100.0 - 2343.55
使用decimalformat
我们也可以使用DECIMALFORMAT到2个小数位。
package org.igi.theitroad;
import java.text.DecimalFormat;
public class DecimalFormatMain {
public static void main(String[] args) {
double d=2343.5476;
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("Rounded double (DecimalFormat) : " + df.format(d));
}
}
使用BigDecimal.
我们可以将双倍或者浮动转换为BigDecimal和使用
setScale()循环到2个小数位的方法。
这是一个例子:
package org.igi.theitroad;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalRoundDoubleMain {
public static void main(String[] args) {
double d = BigDecimalRoundDoubleMain.roundDouble(2343.5476, 2);
System.out.println("Rounded Double: "+d);
float f = BigDecimalRoundDoubleMain.roundFloat(2343.5476f, 2);
System.out.println("Rounded Float: "+f);
}
private static double roundDouble(double d, int places) {
BigDecimal bigDecimal = new BigDecimal(Double.toString(d));
bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP);
return bigDecimal.doubleValue();
}
private static float roundFloat(float f, int places) {
BigDecimal bigDecimal = new BigDecimal(Float.toString(f));
bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP);
return bigDecimal.floatValue();
}
}
使用apache common math
你也可以使用 Apache common数学库 回合 double或者 float到2个小数点。
添加以下依赖 pom.xml。
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
我们可以在此处找到Commons-Math的版本。
这是一个例子:
package org.igi.theitroad;
import org.apache.commons.math3.util.Precision;
public class ApacheMathDoubleMain {
public static void main(String[] args) {
double d=2343.5476;
double roundedDouble = Precision.round(d,2);
System.out.println("Rounded double: "+roundedDouble);
float f=2343.5476f;
float roundedFloat = Precision.round(f, 2);
System.out.println("Rounded float: "+roundedFloat);
}
}

