[英]Javascript array calculation and transformation
我目前正在努力編寫收據計算器。 我想map
具有特定值的數組,然后對數字進行四舍五入並將它們轉換為帶有逗號而不是點的字符串。
let ingredients = [0.02, 0.05, 0.5, 1.2]; let map = ingredients.map(x => x * 6); for (let entry of map) { entry.toFixed(2).replace(".", ","); console.log(entry); }
這是我在映射過程中使用quantity
6 得到的結果:
0.12; 0.30000000000000004; 3; 7.199999999999999
但相反,我希望它是這樣的:
0,12; 0,3; 3; 7,2
entry.toFixed(2).replace(".", ",")
不會改變它return
一個新值的entry
。 您需要為條目分配一個新值。
let quantity = 4; let ingridients = [ 0.02, 0.05, 0.5, 1.2 ]; let map = ingridients.map(x => x * quantity); for (let entry of map) { entry = entry.toFixed(2).replace(".", ","); console.log(entry); }
entry.toFixed(2).replace(".", ",");
不會改變entry
。 您需要將其分配給某物。
let formatted = entry.toFixed(2).replace(".", ",")
console.log( formatted )
.toFixed
和replace
都是純的(就像任何其他使用原語的方法一樣),這意味着它們不會改變引用的值本身而是返回一個新值。 如果你願意
console.log(entry.toFixed(2).replace(".", ","));
你會記錄想要的返回值。
您在使用浮點數執行算術運算時所面臨的精度問題的一種解決方案可以使用修正因子來解決。 correction factor
將是您需要乘以浮點數的數字,以便將其轉換為整數。 從這個意義上說,所有算術運算現在都將在整數之間執行。 您可以檢查下一個代碼以了解如何在這種特殊情況下使用correction factor
:
let quantity = 6; let ingredients = [0.02, 0.05, 0.5, 1.2]; // Define a correction factor for arithmetic operations within // the set of float numbers available on ingredients. let cf = Math.pow(10, 2); let map = ingredients.map(x => { let res = (x * cf) * (quantity * cf) / (cf * cf); return res.toString().replace(".", ","); }); let mapRounded = ingredients.map(x => { let res = (x * cf) * (quantity * cf) / (cf * cf); return Math.ceil(res); }); console.log("Original: ", map, "Rounded-Up: ", mapRounded);
.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}
let ingridients = [ 0.02, 0.05, 0.5, 1.2 ]; let quantity = 6; let map = ingridients .map(x => x * quantity) .map(n => n.toFixed(2).replace(".", ",")); for (let entry of map) { console.log(entry); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.