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

Asked

Viewed 67 times

2

The idea is not to have to convert the result to two decimal places every time. Example:

var preco = 10.00

To show these decimal places, I have to put 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 the toFixed(2).

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

  • You can create a function that returns any number already in the format with 2 decimals. But as stated in @Maniero’s reply, there’s no way to do it this way that the question proposes.

2 answers

4


No, this is not possible. Numeric variables store numbers no matter how it is stored.

You can work with the textual representation of the number with the houses you want (note that it uses the number as a 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 approximation error is by turning into string to see how reckless it is to use numerical types with decimals when you want accuracy), or can make some account so that the number is approximately with the amount of houses you want, at least significantly.

Put this way there is nothing difficult, you must control in your code the way to present appropriately.

I take this opportunity to say that monetary value cannot be stored properly or with the standard Javascript numeric type that uses binary floating point. This has been answered before in How to represent money in Javascript?. And yes, most sites you see out there have problems because they’re not made by professionals.

1

There is no way. The number will always be saved in the standard language precision. You will have to continue controlling the number of decimal places when displaying.

Hint: Do not add values after calling . toFixed(2), as this method converts the number to String. So, summing will generate a String concatenation.

console.log(5.5555.toFixed(2) + 10); //5.5610

Browser other questions tagged

You are not signed in. Login or sign up in order to post.