Can you declare a JavaScript variable so that it always has 2 decimal places?

2

The idea is not to have to convert the result to two decimal places at all times. Example:

var preco = 10.00

To show these decimal places, I have to put it like this:

$("#preco").html("R$ " + preco.toFixed(2));

And then if I do any calculations:

preco += 10
$("#preco").html("R$ " + preco.toFixed(2));

Again I have to put toFixed(2) .

So the question is: Is there any way to always leave this variable with two decimal places, without having to use toFixed() multiple times?

    
asked by anonymous 07.11.2018 / 22:34

2 answers

4

No, this is not possible. Numeric variables save numbers no matter how they are saved.

You can work with the textual representation of the number with the houses you want (note that it uses the number as the base, but it is not the number itself) as you have already learned to do (the only way to ensure that you do not have an error of approximation is turning into string to see how reckless it is to use numeric types with decimals when they want accuracy), or you can do some checking so that the number is approximately the number of houses you want, at least significantly. p>

Putting this shape is not hard, you should control the way you present it appropriately in your code.

I take it to say that monetary value can not be properly stored with the default numeric type of JavaScript that uses floating-point binary. This has been answered before in How to represent money in JavaScript? . And yes, most of the sites you see around have problems because they are not made by professionals.

    
07.11.2018 / 22:46
1

There's no way. The number will always be saved in the default precision of the language. You'll have to keep track of the number of decimal places at the time of display.

A hint: Do not add values after calling .toFixed (2), because this method converts the number to String. Then, adding will generate a concatenation of Strings.

console.log(5.5555.toFixed(2) + 10); //5.5610
    
09.11.2018 / 15:20