如何在 Javascript 中应用 C# 等效舍入方法

How to apply C# equivalent rounding method in Javascript

我正在实现一个混合移动应用程序,我必须在其中表示用 C# 编写的桌面应用程序。

对值进行四舍五入时,桌面应用程序和移动应用程序的值不同。

例子

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# 中的值。

注:

我们可以让C#像JS一样表示值,使用Math.Round (7060.625, 2, MidpointRounding.AwayFromZero);

但我没有选择在那里改变。

编辑 1

小数点四舍五入不固定。它由用户在移动应用程序中选择。

您需要自定义实现舍入以实现 "banker's rounding" 或偶数舍入。

发件人:

Gaussian/banker's rounding in JavaScript

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

如果您同时控制客户端和服务器端,您可以遵循这个超级简单的模式,它适用于边缘情况和常规情况:

让我们看看 2.155、2.145(中点问题)和 2.166、2.146(常规)。

C#:

public static decimal RoundFromJavaScript(this Decimal value)
{
    return Decimal.Round(value, 2, MidpointRounding.AwayFromZero);
}

//-Midpoint Issue 
RoundFromJavaScript(2.155); --> 2.16             
RoundFromJavaScript(2.145); --> 2.15
//-Regular 
RoundFromJavaScript(2.166); --> 2.17             
RoundFromJavaScript(2.146); --> 2.15

*我省略了小数点m,应该是2.155m

JavaScript:

function roundToTwo(num) {
    return +(Math.round(num + "e+2") + "e-2");
}

//-Midpoint Issue
roundToTwo(2.155) --> 2.16           
roundToTwo(2.145) --> 2.15

//-Regular
roundToTwo(2.166) --> 2.17            
roundToTwo(2.146) --> 2.15