在Java中,有几种方法可以将float
或double
舍入到小数点后double
。
注意
阅读此RoundingMode
1. DecimalFormat
DecimalExample.java
package com.mkyong;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalExample {
private static DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
double input = 1205.6358;
System.out.println("salary : " + input);
// DecimalFormat, default is RoundingMode.HALF_EVEN
System.out.println("salary : " + df.format(input)); //1205.64
df.setRoundingMode(RoundingMode.DOWN);
System.out.println("salary : " + df.format(input)); //1205.63
df.setRoundingMode(RoundingMode.UP);
System.out.println("salary : " + df.format(input)); //1205.64
}
}
输出量
salary : 1205.6358
salary : 1205.64
salary : 1205.63
salary : 1205.64
2. BigDecimal
BigDecimalExample.java
package com.mkyong;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalExample {
public static void main(String[] args) {
double input = 3.14159265359;
System.out.println("double : " + input);
BigDecimal bd = new BigDecimal(input).setScale(2, RoundingMode.HALF_UP);
double salary = bd.doubleValue();
System.out.println("salary : " + salary);
}
}
输出量
salary : 1205.6358
salary : 1205.64
3. Math.round
MathExample.java
package com.mkyong;
public class MathExample {
public static void main(String[] args) {
double input = 1205.6358;
System.out.println("salary : " + input);
double salary = Math.round(input * 100.0) / 100.0;
System.out.println("salary : " + salary);
}
}
输出量
salary : 1205.6358
salary : 1205.64
说明,仅用于学术目的,保留三位小数, *1000
input = 1205.6358;
Math.round(input * 100.0) / 100.0;
Math.round(120563.58) / 100.0;
120564 / 100.0;
salary = 1205.64
参考文献
- DecimalFormat JavaDocs
- BigDecimal JavaDocs
- RoundingMode JavaDocs
- 数学JavaDocs
- 如何在Java中将double / float值四舍五入到2个小数点
翻译自: https://mkyong.com/java/how-to-round-double-float-value-to-2-decimal-points-in-java/