传统意义的四舍五入计算
看看net的四舍五入:
static void Main(string[] args) { Console.WriteLine(Math.Round(1.015, 2)); Console.WriteLine(Math.Round(1.0151, 2)); Console.WriteLine(Math.Round(1.0149, 2)); Console.ReadLine(); }
Output:
1.01 1.02 1.01
可以看出不是我们想要的四舍五入。
Code:
/// <summary> /// 四舍五入计算 /// </summary> /// <param name="value"></param> /// <param name="digit"></param> /// <returns></returns> public double Round(double value, int digit = 0) { return Round(Convert.ToDecimal(value), digit); } public double Round(decimal value, int digit = 0) { decimal vt = Convert.ToDecimal(Math.Pow(10, digit)); //1.乘以倍数 + 0.5 decimal vx = value * vt + 0.5m; //2.向下取整 decimal temp = Math.Floor(vx); //3.再除以倍数 return Convert.ToDouble(temp / vt); }
static void Main(string[] args) { Console.WriteLine(Round(1.015, 2)); Console.WriteLine(Round(1.0151,2)); Console.WriteLine(Round(1.0149, 2)); Console.ReadLine(); }
Output:
1.02 1.02 1.01
C#用double,float浮点计算会有误差,所以切换成decimal计算。
=============================================================================
Js端:
toFixed
console.log(1.049.toFixed(2)); console.log(1.054.toFixed(2)); console.log(1.055.toFixed(2)); console.log(1.056.toFixed(2)); VM224:1 1.05 VM224:2 1.05 VM224:3 1.05 VM224:4 1.06
发现1.055错误
Math.round
console.log(Math.round(1.049*100)/100); console.log(Math.round(1.054*100)/100); console.log(Math.round(1.055*100)/100); console.log(Math.round(1.059*100)/100); VM309:1 1.05 VM309:2 1.05 VM309:3 1.06 VM309:4 1.06
OK
code:
function Round(value, digit) { if(!digit)digit=0; var vt = Math.pow(10, digit); //1.乘以倍数 + 0.5 var vx = value * vt + 0.5; //2.向下取整 var temp = Math.floor(vx); //3.再除以倍数 return temp / vt; }
=================================================
js的浮点计算: