gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:38:01 25 4
gpt4 key购买 nike

<分区>

我想显示一个十进制数的值,包括最后两个(或任何)可见数字(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)
}

谢谢。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com