I currently struggle to program a receipt calculator. I want to map over an array with a specific value, then round the numbers and convert they to a string with commas instead of dots.
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);
}
This is what I get using a quantity of 6 on the mapping procedure:
0.12; 0.30000000000000004; 3; 7.199999999999999
But instead, I want it to be like:
0,12; 0,3; 3; 7,2
5 Answers 5
entry.toFixed(2).replace(".", ",") doesn't change the entry it return a new value.You need to assign entry a new value.
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);
}
Comments
entry.toFixed(2).replace(".", ","); doesn't change entry. You need to assign it to something.
let formatted = entry.toFixed(2).replace(".", ",")
console.log( formatted )
Comments
Both .toFixed and replace are pure (as any other method working with primitives) that means they do not change the referenced value itself but return a new value. If you'd do
console.log(entry.toFixed(2).replace(".", ","));
you would log the wanted returned value.
Comments
One solution to the precision problem you are facing when performing arithmetic operations with float numbers could be approached using a correction factor. A correction factor will be that number you need to multiply to the float number so that it gets converted into an integer. In this sense, all the arithmetic operations will now perform between integers numbers. You can check the next code to see how to use a correction factor in this particular case:
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;}
2 Comments
Math.ceil(). I have updated my answer, check if this helps you.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);
}
ingredients, notingridients.