JavaScript 中双精度和浮点精度之间的转换

Mar*_*mus 2 javascript floating-point ieee-754

如何将数字从双精度转换为单精度并返回?

例如,我在 Java/C/C# 中有这样的:

double x = 0.00001;
float f = (float)x; // should be 0.000009999999747378752 not 0.0000100000000000000008180305391403
int n = Math.floor(1001 * f / x); // should be 1000 not 1001.
Run Code Online (Sandbox Code Playgroud)

(别问。这是一些毛茸茸的 C 代码的简化版本,我需要 1:1 移植它)

另一个例子:

double y = Math.floor((double)(float)5.999999876); // should be 6.0
Run Code Online (Sandbox Code Playgroud)

我已经尝试过的:

var f:float = x; // syntax error
var f = x as float; // syntax error
var f = parseFloat(x); // returns full double-precision (0.0000100000000000000008180305391403)
var f = toFixed(x, ...); // Can't use this as float is not defined by number of decimal places but number of binary places.
Run Code Online (Sandbox Code Playgroud)

我正在使用 Rhino(作为 Java 7 的一部分),它也应该与 Nashorn(作为 Java 8 的一部分)兼容。如果这有帮助的话,我可以访问整个公共 Java API。


[编辑]我做了一些更多的实验,看来问题不在于浮点转换,而在于浮点操作。我确实需要处理器中的 FPU 来执行单精度运算fmul。如果在双精度数中包含浮点精度版本,1001 * f则不起作用。获得精确结果的唯一方法是执行 32 位乘法,然后获得结果。f0.000011001f * 0.00001f