如何在Javascript中应用C#等效的舍入方法 [英] How to apply C# equivalent rounding method in Javascript
问题描述
我正在实现一个混合移动应用程序,其中我必须代表用C#编写的桌面应用程序.
I am implementing an Hybrid mobile application in which I have to represent our Desktop application written in C#.
四舍五入一个值时,桌面应用程序和移动应用程序中的值不同.
When rounding off a value, the value differs between Desktop and Mobile application.
示例
C#中使用的代码:
Math.Round (7060.625, 2); // prints 7060.62
Math.Round (7060.624, 2); // prints 7060.62
Math.Round (7060.626, 2); // prints 7060.63
JS中使用的代码:
+(7060.625).toFixed(2); // prints 7060.63 (value differs)
+(7060.624).toFixed(2); // prints 7060.62
+(7060.626).toFixed(2); // prints 7060.63
如何更改JS代码以表示C#中的值.
How can I change the JS code to represent the value as in C#.
注意:
我们可以使用 Math.Round(7060.625,2,MidpointRounding.AwayFromZero);
但是我没有选择在那里更改.
But I have no option to change in there.
编辑1
四舍五入是不固定的.由用户在移动应用程序中选择.
Rounding off decimals is not fixed. It is chosen by user in mobile application.
推荐答案
您需要自定义四舍五入实现银行家四舍五入"或甚至四舍五入".
You need a custom implementation of rounding to implement "banker's rounding" or to-even rounding.
发件人:
function evenRound(num, decimalPlaces) {
var d = decimalPlaces || 0;
var m = Math.pow(10, d);
var n = +(d ? num * m : num).toFixed(8); // Avoid rounding errors
var i = Math.floor(n), f = n - i;
var e = 1e-8; // Allow for rounding errors in f
var r = (f > 0.5 - e && f < 0.5 + e) ?
((i % 2 == 0) ? i : i + 1) : Math.round(n);
return d ? r / m : r;
}
console.log( evenRound(1.5) ); // 2
console.log( evenRound(2.5) ); // 2
console.log( evenRound(1.535, 2) ); // 1.54
console.log( evenRound(1.525, 2) ); // 1.52
这篇关于如何在Javascript中应用C#等效的舍入方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!