JS- toFixed 返回一个字符串,但我需要一个数字到 6 位

Mic*_*eat 7 javascript precision decimal tofixed

我正在使用另一个我无法控制且看不到的代码库。我可以向它发送输入,它会将输出返回给我。这个代码库也没有指定它是用什么写的,但这并不重要,因为我只需要传递它的数字,它就会把它的输出数字交给我。我只知道预期的输入和输出是什么。

我必须处理的输入之一要求我提供一个长度正好为 6 位小数的输入。我的大多数数字都远高于 6 位小数,所以我可以四舍五入或截断它,但如果它被四舍五入或随机恰好是一个像0.125or的数字0.5,我无法输入正确的数字。

例如,如果我有一个像 那样的数字0.5,那是一个有效且合法的数字,但是我输入它的函数不会接受它并且会出错,因为它不是像0.500000is一样精确到 6 位小数的数字。我也无法输入 的字符串"0.500000",因为它也会出错,因为它正在寻找一个数字,而不是一个字符串。

无论如何,即使在数字末尾有额外的死零,本机 JavaScript 是否也能保持数字的特定精度?

例子:

(1/2).toFixed(6) === "0.500000" // the toFixed() function returns a *String*, not a *Number*.

(1/2).toFixed(6) /1 === 0.5 // dividing by 1 coerces it to a Number, but drops the decimals back off the end.

Number( (1/2).toFixed(6) ) === 0.5 // Trying to convert it into a Number using the Number Constructor does the same as  the example above it.
Run Code Online (Sandbox Code Playgroud)

*编辑:要清楚,我需要一个小数点后 6 位的数字,而不是字符串。

joe*_*ler 7

尝试这个:

parseFloat(val.toFixed(6))
Run Code Online (Sandbox Code Playgroud)


l.g*_*los 0

function myFunction() {

        var a = (1/2).toFixed(6) + "<br>";
        var b = parseFloat(a).toFixed(6) + "<br>";
       
        var x = new Decimal(123.4567) + "<br>";
         var n = a + b + c;
        document.getElementById("demo").innerHTML = n;
    }
Run Code Online (Sandbox Code Playgroud)
<script src="https://raw.githubusercontent.com/MikeMcl/decimal.js/master/decimal.min.js">
</script>

<button onclick="myFunction()">Try it</button>

    <p id="demo"></p>
Run Code Online (Sandbox Code Playgroud)

数字不包含有关有效数字的信息;值 2 与 2.0000000000000 相同。当您将四舍五入的值转换为字符串时,您可以使其显示一定数量的数字。

函数需要 6 位十进制数,这似乎有点奇怪。但是看看这个图书馆,它有很多适合你的东西,它可能对你有帮助

十进制