Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何根据值的小数点更改.toFixed()?_Javascript - Fatal编程技术网

Javascript 如何根据值的小数点更改.toFixed()?

Javascript 如何根据值的小数点更改.toFixed()?,javascript,Javascript,我想显示十进制数的值,包括最后两个(或任何)可见数字(0旁边) 以下是我想归档的示例: Input: 1 Output: 1 Input: 0.1 Output: 0.1 Input: 0.000123 Output: 0.00012 //stripped down the "3", only show nearest 2 digits (12) Input: 0.00102 Output: 0.0010 //stripped down the "2", only show nearest

我想显示十进制数的值,包括最后两个(或任何)可见数字(0旁边)

以下是我想归档的示例:

Input: 1
Output: 1

Input: 0.1
Output: 0.1

Input: 0.000123
Output: 0.00012 //stripped down the "3", only show nearest 2 digits (12)

Input: 0.00102
Output: 0.0010 //stripped down the "2", only show nearest 2 digits (10)

Input: 0.000000100000000000000009999
Output: 0.00000010
我试过硬编码,但我认为它没有那么可靠。有更好的方法吗

function strip(val, length){
    var val = val.toString()
    var integer = val.split(".")[0]
    var decimals = val.split(".")[1]
    var reachedFirstDec = false
    var count = 0
    var result = ""
    var i = 0
    while (count !== length) {

        if (reachedFirstDec) {
            count++
        }

        if (decimals[i] !== "0" && !reachedFirstDec) {
            console.log(`Reached first non 0 character at ${i}`)
            reachedFirstDec = true
            count++
        }
        result = result + decimals[i]
        i++
        console.log(result);
    }
    return parseFloat(integer + "." + result)
}

谢谢。

您可以取数字的10的对数,然后将
调整为字符串
,以获得想要的结果

对于动态长度,可以在数字的所需长度上使用闭包

函数x(l){
返回函数(v){
var e=数学地板(数学对数10(v));
返回e<0?v.toFixed(l-1-e):v;
}
}
变量数组=[1000,1,0.1,0.0001232456,0.0010234567,0.0000001000000000000009999];
console.log(array.map(x(2));
console.log(array.map)(x(3));

console.log(array.map(x(4))非常感谢,是否可以使用2以外的“动态”长度?(就像我上面丑陋的例子)例如(长度=3):0.001034=0.00103?