Javascript中的单精度浮点仿真(float32)

时间:2010-10-31 09:50:35

标签: javascript floating-point emulation

是否有可能以某种方式模拟Javascript中的单精度浮点数?根据Doug Crockford的博客“Number is 64-bit floating point”,但是我必须使用单一来移植C ++算法来计算单精度浮点误差。

2 个答案:

答案 0 :(得分:6)

ES6标准有Math.fround(),它将float64转换为float32然后再返回,有效地将float舍入为float32精度。有关详细信息,请参阅this article

答案 1 :(得分:-1)

试试这个JavaScript函数。它使用.toFixed(6)将数字四舍五入到小数点后六位。

function ToSingle(s) {
 s = s.toString().toUpperCase();
 if (s.indexOf("E") == -1) s = parseFloat(s).toExponential().toUpperCase();
 if (s.indexOf("E") == -1) return s

 var o = s.split("E");
 var s1 = o[0];

 if (s1.indexOf(".") == -1) return s
 if (s1.split(".")[1].length < 7) return s;

 var num = parseFloat(s1);
 if (num + "" == "NaN") return s;

 return num.toFixed(6) + "E" + o[1];
}
相关问题