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

查看:90
本文介绍了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 我得到:

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

根据defualt 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天全站免登陆