C#中保留几位小数的问题

[ 2006-04-19 13:15:09 | 作者: admin ]
字号: | |
方法一、
double d=123.1256521;
string output=d.ToString("f3");

方法二、
new DecimalFormat("0.00").format(*******);

方法三、
运行结果:
        Math.Round(3.44, 1) = 3.4
        Math.Round(3.45, 1) = 3.4
        Math.Round(3.46, 1) = 3.5
        -----------------------------------------------
        Math.Round(3.54, 1) = 3.5
        Math.Round(3.55, 1) = 3.6
        Math.Round(3.56, 1) = 3.6
        -----------------------------------------------
        Math.Round(3.64, 1) = 3.6
        Math.Round(3.65, 1) = 3.6
        Math.Round(3.66, 1) = 3.7
        -----------------------------------------------
        Math.Round(3.74, 1) = 3.7
        Math.Round(3.75, 1) = 3.8
        Math.Round(3.76, 1) = 3.8

    我想您应该知道这个是与我们习惯的四舍五入不同。
    这种舍入方法叫做银行家舍入(Banker'sRound),这就是已经规定下来的标准、Round的标准、世界的标准。
    也许我们习惯把Round与四舍五入等同,但是公式可能应该这样写。
    Round <> 四舍五入

方法四、
1 /**
   2 * Contains static utility methods.
   3 */
   4 public class BOUtils {
   5
   6 public static Double getRoundedDouble( double unroundedValue ){
   7 // Get the integer portion of the value
   8 double intPortion = Math.floor( unroundedValue );
   9
10 // Get the unrounded decimal portion
11 double unroundedDecimalPortion = ( unroundedValue - intPortion );
12
13 /* ALERT - This next code interferes with I18N. We eventually need */
14 /* to change this not assume only round to 2 decimal places. */
15
16 /* Multiply the decimal places by 100, which shitfs the decimal point
17 /* two places to the left. Then round it so that we get a round to
18 /* two decimal places. For example, if we started with 17.655 and stripped
19 /* off the int portion, which left .655. After we shift, we are left with
20 /* 65.5. Then a round will gives us 66. We can then put it all back
21 /* together */
22 double roundedDecimalPortion = Math.round( unroundedDecimalPortion * 100 );
23
24 // Shift the decimal point back two places to the right
25 roundedDecimalPortion = roundedDecimalPortion / 100;
26
27 // Add the int portion and decimal portions back together
28 double total = intPortion + roundedDecimalPortion;
29
30 return new Double( total );
31 }
32 }
[最后修改由 admin, 于 2007-03-30 15:41:42]
评论Feed 评论Feed: http://blog.xg98.com/feed.asp?q=comment&id=502

这篇日志没有评论。

此日志不可发表评论。