import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
1:問題如何把double dou=1234.5678;進行保留兩位的四寫五入爲dou=1234.57
BigDecimal bigDecimal = new BigDecimal(dou,new MathContext(6,RoundingMode.HALF_EVEN));
System.out.println("round ---->"+bigDecimal.doubleValue());
這6指定要顯示的長度。
2.Math.ceil求最小的整數但不小於本身.
Math.round求本身的四捨五入。
Math.floor求最大的整數但不大於本身.
問題
我要進行四捨五入或取近似值.
解決辦法
用 Math.round( ) 進行四捨五入, Math.floor( ) 和 Math.ceil( ) 進行上下近似值。NumberUtilities.round( ) 方法可自定義取值。
討論
很多情況我們需要得到整數部分而不是帶有小數的浮點數。比如計算出結果爲 3.9999999 ,期望的結果應該是4.0。
Math.round( ) 方法進行四捨五入計算:
trace(Math.round(204.499)); // 顯示: 204
trace(Math.round(401.5)); // 顯示: 402
Math.floor( ) 方法去掉小數部分,Math.ceil( ) 方法去掉小數部分後自動加1:
trace(Math.floor(204.99)); // 顯示: 204
trace(Math.ceil(401.01)); // 顯示: 402
如果我想要把90.337 四捨五入到 90.34,可以這麼寫:
trace (Math.round(90.337 / .01) * .01); //顯示: 9.34
trace (Math.round(92.5 / 5) * 5); // 顯示: 95
trace (Math.round(92.5 / 10) * 10); // 顯示: 90
更好的辦法是用自定義函數NumberUtilities.round( ) ,它需要兩個參數:
number :要舍入的數字
roundToInterval :間隔值
NumberUtilities 類在 ascb.util 包中。
imported ascb.util.NumberUtilities導入
trace(NumberUtilities.round(Math.PI)); // Displays: 3
trace(NumberUtilities.round(Math.PI, .01)); // Displays: 3.14
trace(NumberUtilities.round(Math.PI, .0001)); // Displays: 3.1416
trace(NumberUtilities.round(123.456, 1)); // Displays: 123
trace(NumberUtilities.round(123.456, 6)); // Displays: 126
trace(NumberUtilities.round(123.456, .01)); // Displays: 123.46
來源於http://esffor.javaeye.com/blog/96075
Math.round(par)實現機制內部調用(long)Math.floor(par+1/2)
public static long round(double a)
- Returns the closest
long
to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to typelong
. In other words, the result is equal to the value of the expression:(long)Math.floor(a + 0.5d)
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 ofLong.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 ofLong.MAX_VALUE
.