admin管理员组文章数量:1363838
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.
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.
Share Improve this question edited Nov 2, 2010 at 16:13 qqryq asked Oct 31, 2010 at 9:50 qqryqqqryq 1,9243 gold badges18 silver badges21 bronze badges 1- Two ments: (1) The last word should be "error", not "mistake". "error" is a technical term in dealing with floating point putations. (2) Can you give some context for why you need the error in a floating point calculation? It may be that there are other ways to achieve your ultimate goal without emulating single precision in javascript. – Philip Starhill Commented Nov 1, 2010 at 18:57
2 Answers
Reset to default 12The 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.
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];
}
本文标签: floating pointSingle precision float emulation in Javascript (float32)Stack Overflow
版权声明:本文标题:floating point - Single precision float emulation in Javascript (float32) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743765694a2535195.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论