Javascript 和 C# 舍入地狱 [英] Javascript and C# rounding hell

查看:26
本文介绍了Javascript 和 C# 舍入地狱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如您所知,由于 C# 中的天才舍入规则,我们得到以下值:

As you know due to genius rounding rule in C# we are getting the following values:

decimal d = 2.155M;
var r = Math.Round(d, 2); //2.16

decimal d = 2.145M;
var r = Math.Round(d, 2); //2.14

现在在 Javascript 客户端,我得到:

Now on client side in Javascript I am getting:

2.155.toFixed(2)
"2.15"

2.145.toFixed(2)
"2.15"

kendo.toString(2.155, 'n2')
"2.16"

kendo.toString(2.145, 'n2')
"2.15"

但是我在后端进行了验证,但由于这个原因而失败.处理这种情况的正确方法是什么?如何同步 C#Javascript 舍入以确保它们都舍入到相同的值?

But I have validations in the backend that is failing due to this. What is the correct way to deal with this kind of situation? How can I sync C# and Javascript rounding to be sure they both round to the same values?

推荐答案

有一个 C# 的 Math.Round 中的过载 接受一个指标来确定当数字介于其他两个之间时如何舍入.例如.MidPointToEven 将 0.5 舍入为零,因为零是最近的偶数:

There´s an overload in C#´s Math.Round accepting an indicator to detmerine how to round when number is half-way between two others. E.g. MidPointToEven rounds the 0.5 to zero as zero is the neartest even number:

decimal d = 2.155M;
var r = Math.Round(d, 2, MidPointRounding.AwayFromZero); //2.16

decimal d = 2.145M;
var r = Math.Round(d, 2, MidPointRounding.AwayFromZero); //2.15

根据默认的 MidPointToEven 使用,您的数字将始终四舍五入到最接近的偶数.你会得到这些结果:

As per defualt MidPointToEven is used your number will allways be rounded to the nearest even number. Thuis you get those results:

2.155 --> 2.16
2.145 --> 2.14

这篇关于Javascript 和 C# 舍入地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆