gpt4 book ai didi

javascript - 如何使javascript对值的位数敏感?

转载 作者:行者123 更新时间:2023-12-02 18:30:41 25 4
gpt4 key购买 nike

假设我们有一个数组 [0.09, 870, 499],我们想要获取数组值:[0.1, 1000, 100]?

我尝试过什么:

var logarithmicRound = function(val) {
var degree = Math.round(Math.log(val) / Math.LN10);

if(Math.pow(10, degree) - val > val) {
--degree;
}
return Math.pow(10, degree);
};

console.log(logarithmicRound(0.05));
console.log(logarithmicRound(0.7));
console.log(logarithmicRound(49));
console.log(logarithmicRound(50));
console.log(logarithmicRound(400));
console.log(logarithmicRound(800));

// prints
//0.1
//1
//10
//100
//100
//1000

然而它看起来很丑......但它正是我所需要的。

最佳答案

我使用了几个函数来对数字进行四舍五入,它们可能很有用。

function roundTo2(value){
return (Math.round(value * 100) / 100);
}



function roundResult(value, places){
var multiplier = Math.pow(10, places);
return (Math.round(value * multiplier) / multiplier);
}

您显然需要对数字进行舍入并放入数组/提取、舍入、放回 - 不如其他人的答案那么有效

关于javascript - 如何使javascript对值的位数敏感?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17831597/

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