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