Recently, I met a requirement. I need create an input to recive amount from user properly.
At first, I want input number because the backend used bigint as storage type. It’s quite troublesome to convert between String and Number. What’s more troublesome is that I need to convert the numbers into units. But I know the number of JS is based on IEEE754 basic 64-bit binary floating-point. So there must be an accuracy loss problem here. Beacuse I was under the impression that as long as it was expressed in floating point numbers, then there must be numbers that could not be expressed accurately.
I remembered the example I saw before. I tried in my Chrome’s console.
console.log(0.2 + 0.1)
// 0.30000000000000004
This means the number 0.3 cannot be represented accurately. So I then proceeded with the following attempt.
const num = 0.3;
console.log(num);
// 0.3
I was surprised to find that the printout was actually accurate. But then I immediately calmed down and decided that this number was stored inaccurately at the memory. Even through it can be stored accurately, what about passed by json?
So this is my first question. Am I correct in this opinion? And how to explain the accurate print of 0.3?
In the end, I used string as input and regex to validate the string is a valid number of money. Then pass the string to the backend and let th server to parse and store.
So this is my second question. Is the method correct? Or there may be some other way better? Please guide me.