簡體   English   中英

將數字四舍五入為 1

[英]Rounding numbers down to 1

我想要做的是將左邊的數字四舍五入到 1。例如,如果一個數字是 12345.6789,則向下舍入到 100000.0000.. 如果數字是 9999999.9999,則向下舍入到 1000000.0000。 還希望它適用於小數,所以如果一個數字是 0.00456789,把它四舍五入到 0.00100000。

在這個例子中,5600/100000 = 0.056,我希望它四舍五入到 0.01。 我在 LUA 腳本中使用以下代碼,它運行良好。

function rounding(num)
  return 10 ^ math.floor((math.log(num))/(math.log(10)))
end
print(rounding(5600/100000))

但是如果我對 Javascript 使用相同的值,它會返回 -11,而不是 0.01。

function rounding(num) {
  return 10 ^ Math.round((Math.log(num))/(Math.log(10)))
}
console.log((rounding(5600/100000)).toFixed(8))

任何幫助或指導將不勝感激。

您可以對 log 10值進行下限,並以 10 為底取回指數值的值。

不能保存帶零的小數位。

 const format = number => 10 ** Math.floor(Math.log10(number)); var array = [ 12345.6789, // 100000.0000 this value as a zero to much ... 9999999.9999, // 1000000.0000 0.00456789, // 0.00100000 ]; console.log(array.map(format));

檢查此代碼。 它單獨處理字符。 它似乎可以完成這項工作。

 function rounding(num) { const characters = num.toString().split(''); let replaceWith = '1'; characters.forEach((character, index) => { if (character === '0' || character === '.') { return; }; characters[index] = replaceWith; replaceWith = '0'; }); return characters.join(''); } console.log(rounding(12345.6789)); console.log(rounding(9999999.9999)); console.log(rounding(0.00456789)); console.log(rounding(5600/100000));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM