Realized bug was caused by decimal number precision 'bug' after struggling for 2 hours

I was doing the final certification challenge for javascript, and I realized the bug was caused by decimal numbers not calculating accurately.

I just used Math.round() on basically every variable that can become a decimal. What’s a better way of dealing with decimal numbers? Rounding every number seems inconvenient.

There are bunch of methods to deal with rounding:

Math.ceil
Math.floor
Number.toFixed
Number.toPrecision

I don’t know what was your approach to cash register, so you can do research and figure out if some of these can be useful for you.

And, more importantly, you can go for some shenanigans like:

a = 36.75;

splittedA = a.toString().split('.').map(elem => Number(elem));

console.log(splittedA)//[ 36, 75 ]

//with that we can deal with decimal part as as with integer
// and avoid fraction-related annoyance

I am improvising here, but I think general idea is clear in the above.

Just use integers. As with many other languages, JS doesn’t have decimal number support built in (it would have limited use). All numbers in JS are of one type, floating point (f32). You can model decimals (for example, using two integers for each single decimal number), and there are several good libraries for doing decimal maths, but it will always be quite fiddly and fairly inefficient – just using integers is the easiest solution, then format to what you want at the end. So for this, work in cents, not dollars – 121 not 1.21

Edit: Just for clarity, floating point is a way of representing real numbers, but a. it’s constrained by the memory available for each number (32 bits in this case), and b. computers use binary, not decimal. So it’s literally impossible to accurately represent (for example) 0.1 or 0.2, because those are recurring in binary, so have to be rounded, and hence you get errors when trying to do maths with them.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.