关于java的四舍五入函数,精确到小数点后n位的方法。
1. 四舍五入函数
- Math.round(double a)
- Math.rint(double a)
long java.lang.Math.round(double a)
Returns the closest long to the argument, with ties rounding to positive infinity.
Special cases:
If the argument is NaN, the result is 0.
If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE.
If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.
Parameters:
a a floating-point value to be rounded to a long.
Returns:
the value of the argument rounded to the nearest long value.
Math.round(2.50);
运行结果:3
Math.round(2.49);
运行结果:2
double java.lang.Math.rint(double a)
Returns the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close, the result is the integer value that is even. Special cases:
If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
Parameters:
a a double value.
Returns:
the closest floating-point value to a that is equal to a mathematical integer.
Math.rint(2.51)
运行结果:3.0
Math.rint(2.50);//此处特殊,2.50也认为是舍,而比2.50大,才能入。
运行结果:2.0
----------
2. 舍函数Math.floor(2.8)
double java.lang.Math.floor(double a)
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. Special cases:
If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
Parameters:
a a value.
Returns:
the largest (closest to positive infinity) floating-point value that less than or equal to the argument and is equal to a mathematical integer.
Math.floor(2.8)
运行结果:2.0
Math.floor(2.3)
运行结果:2.0
3. 保留n位小数(精确到n位小数)
DecimalFormat d = new DecimalFormat("#.0");
System.out.println(d.format(2.5563));
运行结果:2.6
"#.0"表示保留一位小数
"#.00"表示保留两位小数
"#.000"表示保留三位小数
"#.0000"表示保留四位小数
...
...
以此类推