在Java语言中四舍五入,使其与C#匹配

问题描述 投票:0回答:1

我有一个用nodejs编写的应用程序。该应用程序需要计算海事征费。计算需要匹配端口的结果。端口中的征费计算器用C#编写。

这是Javascript代码:

console.log('Testing rounding -- js')
nrt = 34622
c = 0

if (nrt <= 5000) c = nrt * 0.405
else if (nrt > 5000 && nrt <= 20000) c = 2025 + ( (nrt - 5000) * 0.291)
else if (nrt > 20000 && nrt <= 50000) c = 6390 + ( (nrt - 20000) * 0.24)
else c = 13590 + ( (nrt - 50000) * 0.18)

var p = nrt * 0.1125

var t = c + p

console.log(t)
console.log(t.toFixed(2))

结果:

Testing rounding -- js
13794.255
13794.25

这是C#代码:

using System;

namespace sample1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Testing rounding -- csharp");

            decimal nrt = 34622;
            decimal  c = 0;
            if (nrt <= 5000) c = nrt * (decimal) 0.405;
            else if (nrt > 5000 && nrt <= 20000) c = 2025 + ( (nrt - 5000) * (decimal) 0.291);
            else if (nrt > 20000 && nrt <= 50000) c = 6390 + ( (nrt - 20000) * (decimal) 0.24);
            else c = 13590 + ( (nrt - 50000) * (decimal) 0.18);

            decimal p = nrt * (decimal) 0.1125;

            decimal t = c + p;

            Console.WriteLine(t);
            Console.WriteLine(Decimal.Round(t, 2));
        }
    }
}

结果:

Testing rounding -- csharp
13794.2550
13794.26

[请注意,我一点都不了解C#。我意识到它具有“十进制”类型,该类型小于[[128位数据类型,适合财务和货币计算。它具有28-29位精度

据我所知,JavaScript无法处理128位数据类型。

我也想知道问题是否可能在于四舍五入的不同实现。

我写这篇文章是因为我还补充说13794.2550在整个系统中难以可靠地四舍五入。这是一个完全不同的兔子洞。

但是,例如,使用rounding function blatantly stolen from stackoverflow

function r(n, decimals) { return Number((Math.round(n + "e" + decimals) + "e-" + decimals)); } console.log(r(13794.2550,2)) console.log(13794.2550.toFixed(2))

结果:

13794.26 <--- this is what I want! But, is it reliable? 13794.25

舍入函数似乎给出相同的结果。因此,也许我遇到了“舍入实现”问题,而不是“精度不够”问题。但是,它可靠吗?

(即c#Decimal.Round函数的实现与rounding function blatantly stolen from stackoverflow完全一样吗?

javascript c# rounding rounding-error
1个回答
0
投票
我认为您遇到的问题是因为您使用的是不同类型的舍入函数。

在JS部分中,您使用的是toFixed(),而不是Math.round()。 toFixed不在意。这是一个Cutt-off功能。您应该能够使用Math.round()获得与C#中相同的结果。它们均由Microsoft维护,因此通常它们的工作原理非常相似,有时具有相同的库实现(从用户角度而言)。

Math.round(num) vs num.toFixed(0) and browser inconsistencies

因此,您使用的第二种实现是可靠的。如果您担心128字节转换,请尝试使用double而不是decimal,并检查是否与double的结果相同是64位,如果需要进一步测试,请使用32位的float

© www.soinside.com 2019 - 2024. All rights reserved.