// convert the number to it's standard value (kilogram)
standard = parseFloat(unit / from);
// now convert it to the new measurement unit
converted = parseFloat(standard * eval(to));
If you enter a number less than one, for example ‘0.234234234’ and try converting to a new unit by changing the drop-down. Any number less than 1 and it’ll go to zero.
Any idea what is going on here?
Although the error is caused because of the usage of
parseInt()where you should have usedparseFloat(), there’s a whole lot more wrong with your code.eval()is evil, and you’re using it where you don’t even need it or could easily replace it with a far better solution.eval(to)is unnecessary sincetois already a number.evalis used to use a string to access a global variable. This is a very bad idea, and it’s much more appropriate to store your unit/value mappings in an object literal, such asvar units = { gram: 1000, kilogram: 1, ... }Then, you can access the value by simply using the string as index, such asunit["milligram"].parseFloat()when you already have a number, such as withunit / fromorstandard * to)from) in the function are global, because you’re missing thevarkeyword in front.Here’s a somewhat “fixed” fiddle.