C# float double decimal 金额舍入 区别

    技术2026-06-07  6

    //函数功能:

    value要转换的值

    digits小数位数

     truncatetype:截取类型 全入 全舍 四舍五入

    下面是原先代码

    public static double ConvertDouble(double value, int digits, int truncatetype) { double tempPow = System.Math.Pow(10,digits); double tempValue = value * tempPow * 10; tempValue = System.Math.Truncate(tempValue); tempValue /= 10; switch(truncatetype) { case 1: //上取 tempValue = System.Math.Ceiling(tempValue); break; case 2: //下取 tempValue = System.Math.Floor(tempValue); break; default: tempValue = System.Math.Round(tempValue); break; } return (tempValue / tempPow); }

     

    public static float ConvertFloat(float value, int digits, int truncatetype) { return Convert.ToSingle(ConvertDouble(Convert.ToSingle(value), digits, truncatetype)); }

     

    主要使用ConvertFloat这个函数在测试过程中发现1.8变成1.79这是两位小数。最后修正的代码

    public static float ConvertFloat(float value, int digits, int truncatetype) {  float tempPow = Convert.ToSingle(System.Math.Pow(10, digits)); //移动小数点到digits位  float tempValue = value * tempPow * 10.0F; //继续移动一位小数  tempValue = Convert.ToSingle(System.Math.Truncate(tempValue)) / 10.0F; //截取后移回小数位  switch (truncatetype) //截取 { case 1: //上取 tempValue = Convert.ToSingle(System.Math.Ceiling(tempValue)) / tempPow; break; case 2: //下取 tempValue = Convert.ToSingle(System.Math.Floor(tempValue)) / tempPow; break; default: tempValue = Convert.ToSingle(System.Math.Round(tempValue)) / tempPow; break; } return tempValue ; }

     

    经验:原先的想法,只要将float转换为double即可

    但是调试发现,1.8转换为double后变为1.7999999.....这样就出现问题。但是float类型的值大了以后可能不会出现这样的问题。因为这是单价含义,因此出现问题。

    实在抱歉,又出现问题了。

    在开发环境下没有任何问题,当编译成release执行的时候仍旧出现上述问题。

    最后在网上http://stackoverflow.com找到一个方法,将float转换为decimal可解决问题。经过测试一切OK!

    血的教训,使用金额的时候一定要使用decimal类型。

    最新回复(0)