[英]Obtain two decimal places in JavaScript without rounding to the next bigger number
我有這個JS代碼:
var propertyYield = annualRent / propertyValue * 100.0;
在特定情況下,結果是 4.999。
所以當我這樣做時
propertyYield.toFixed(2)
我得到 5.00 的 propertyYield。
我想要實現的是實際得到 4.99 而不是 5.00 作為四舍五入到兩位小數。
我怎樣才能做到這一點?
更新:正如@kuka 所指出的,由於浮點錯誤數學,這不適用於某些十進制數。 不要使用這個解決方案 - 但是我把它留在這里是為了文檔。
不確定我是否知道一種庫方法可以做到這一點,但快速簡單的老式解決方案是這樣的:
Math.floor(4.999 * 100) / 100.0
您可以使用 Math.floor 和一些額外的算術:
Math.floor(15.7784514000 * 100) / 100
或者將數字轉換為字符串,將數字匹配到小數點后第二位並將其轉換回數字:
Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/))
然后你仍然可以調用 toFixed 來獲取一個小數位數固定的字符串。
var num1 = Math.floor(15.7784514000 * 100) / 100; console.log(num1); var num2 = Number(15.7784514000.toString().match(/^\\d+(?:\\.\\d{0,2})?/)); console.log(num2) console.log(num2.toFixed(2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.