Single precision float emulation in Javascript (float32)

点点圈 提交于 2019-12-19 17:46:28

问题


Is it possible to somehow emulate single precision float in Javascript? According to Doug Crockford's blog "Number is 64-bit floating point", but I have to use single one for porting C++ algorithm which calculates single precision float's error.


回答1:


The ES6 standard has Math.fround() which converts a float64 to float32 and then back again, effectively rounding the float to float32 precision. See this article for details.




回答2:


Try this JavaScript function. It uses .toFixed(6) to round off the number to six decimal places.

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];
}


来源:https://stackoverflow.com/questions/4062632/single-precision-float-emulation-in-javascript-float32

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!