天天看點

Java四舍五入及保留小數點位數

關于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();
運作結果:
Math.round();
運作結果:
           

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()
運作結果:
Math.floor()
運作結果:
           

3. 保留n位小數(精确到n位小數)

DecimalFormat d = new DecimalFormat("#.0");
System.out.println(d.format());
運作結果:
"#.0"表示保留一位小數
"#.00"表示保留兩位小數
"#.000"表示保留三位小數
"#.0000"表示保留四位小數
...
...
以此類推