I have 2 select lists in html, place to enter a number and second place to show the result. It works like a conversion, so when you choose milimeters from the first list and meters from the second it will show you number you entered x 0.001. There is no problem with small numbers (up to 9 digits - I can round these), but when I'm trying to do 1 millimeter to 1 yoctometer (1.0 × 10-21 millimeters) sometimes it is correct, sometimes not. If I add zeros to yoctometer sometimes it will show something like 0.1 + 0.2 = 0.30000000000000004. The problem is I can't round it, because someone can enter like 1000 yoctometers and it won't work. Is there a way to fix this? (look at millimeters -> centimeters, Math.pow)
const config = {
"milimeters": {
"milimeters": v => v * 1,
/* this is only an example */
"centimeters": v => v * Math.pow(10, -21),
"decimeters": v => v * 0.01,
"meters": v => v * 0.001,
"dekameters": v => v * 0.0001,
"hectometers": v => v * 0.00001,
"kilometers": v => v * 0.000001,
"inches": v => v * 0.0393700787,
"feet": v => v * 0.0032808399,
"yards": v => v * 0.0010936133,
"miles": v => v * 0.000000621371192,
},
}
function calculate() {
const listFromV = document.getElementById("listFrom").value;
const listToV = document.getElementById("listTo").value;
const inputPlace = parseFloat(document.getElementById("inputPlace").value);
const fn = config[listFromV][listToV];
document.getElementById("resultPlace").innerHTML = fn(inputPlace);
if (document.getElementById("inputPlace").value == "") {
document.getElementById("resultPlace").innerHTML = "0.00";
}
};
Edit:
1 * Math.pow(10, -21) = 1.0000000000000001e-21 /* not correct */
1000 * Math.pow(10, -21) = 1e-18 /* correct */
10 * Math.pow(10, -29) = 1.0000000000000001e-28 /* not correct */
100 * Math.pow(10, -29) = 1e-27 /* correct */