c# - 小数,javascript 与 C#

标签 c# javascript decimal data-conversion

我正在尝试将 JavaScript 散列函数转换为 C# 散列函数以执行完全相同的操作。我已经完成了 99%,但我遇到了这个自定义函数中使用的小数点的问题。
我不确定为什么,但是这个函数出于某种奇怪的原因将散列值转换为小数,我的问题是生成的小数并不总是相同的长度。 C# 中的小数点要长一些,但长度是统一的。我遇到的问题是因为 C# 中的舍入与 JavaScript 中的舍入工作方式不同 我不知道要舍入多少小数来创建等效长度的字符串。

下面是两个生成的相互附加的十进制字符串的示例。都是从 4,4 和 3 个字符串开始的:

4 char string generates 79957.88183577501
4 char string generates 160933.02806113224
3 char string generates 609.9111294990053

Using the exact same code C# generates using the exact same inputs:

79957.88183577500452161331162
160933.02806113221197323204919
609.91112949900524507144149035

If all strings were the same length it would not be a problem but I have no idea how to determine when JS will generate the longer decimal. Any clues? Comments? Opinions?

Unfortunately the receiving code is still the original JS which simply reverses the process hence I have to duplicate the end result perfectly for all inputs.

EDIT:

Here is the problematic section. Don't ask me why it works like that, I didn't write it.

// oString is a full string to be encoded
// oKey is a key to be used for encoding
function completeHash(oString,oKey) {
    if( oKey.length < 5 ) {
        window.alert( 'The key must be at least 5 characters long' );
        return oString;
    }
    var oKeyNum = new Array(), oOutStr = '', oOp = new Array('+=','/=','-=','*= 0.01 *');
    for (var x = 0; x < oKey.length; x++) {
        oKeyNum[x] = parseInt('0x' + completeEscape(oKey.charAt(x)));
    }

    for( var x = 0, y = ''; x < oString.length; x += Math.round( oKey.length / 2 ), y = 'O.O' ) {
        var theNum = parseInt( '0x' + completeEscape( oString.substr( x, Math.round( oKey.length / 2 ) ) ) );

        // next two lines are problematic with decimals not having equal length
        for( var z = 0; z < oKey.length; z++ ) {
            eval( 'theNum ' + oOp[z % 4] + ' ' + oKeyNum[z] + ';' );
            alert('theNum:' + theNum);
        }

        oOutStr += y + theNum;
    }
    return oOutStr;
}

completeEscape() 函数简单地返回每个字符的 ASCII int 代码。

除了小数点的长度,我让整个事情都很好地工作。

最佳答案

如果您在 javascript 中使用 Number,则在 C# 中使用 double。两者都是 64 位 IEEE 754 数字( double )。您得到相同的值(在验证后更新)。

关于c# - 小数,javascript 与 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13040204/

相关文章:

c# - WPF 数据网格组样式

javascript - 将 transitionend 事件监听器与 react 一起使用以创建过渡

javascript - 如何循环处理请求的 javascript 页面?

javascript - Angular 2 : Directives: capturing click event on children

c# - 如何在多个 visual studio 项目中组织我们的 javascript

c# - DHCP 地址 255.255.255.255

binary - 如何将十进制 (xx.xx) 转换为二进制

c - 如何在C中拆分一个两位数

c# - Linq 到 RSS 提要?

c# - 尽管设置了精度,但 MSSQL 表中的十进制数会四舍五入