How to make all variables in javascript script have two decimal points

146 views Asked by At

community :)

I'm building a webpage and I need to show prices from external javascript variables into HTML table. Variables are declared like this:

var price1 = 256.6;
var price2 = 220.36;

Then I write these variables into HTML with internal script using .innerHTML() function. What I want is to make all variables in external javascript have 2 decimal points. I can use:

var price11 = price1.toFixed(2);
var price22 = price2.toFixed(2);

But I have too many variables to apply the conversion to each of them individually. So is there a way to convert all the variables on the entire script to have two decimal points?

4

There are 4 answers

0
Jagath01234 On BEST ANSWER

As I know there is no way of doing that in core Javascript. You may have to write a on load function or some times there may be libraries to do that. But you will have to find hard for that.

0
aurelius On

You have 2 choices:

  1. either you round the number where is generated (at the source - from the library or endpoint)
  2. or you round them locally
0
Walter Chapilliquen - wZVanG On

If the external file has global variables, you can do this:

//External file
var price1 = 1.2569;
var price2 = 5.5762;

//Script
var tmp, i = 1;

while(tmp = window["price" + i]){
   window["price" + i + "" + i++] = tmp.toFixed(2)
}

document.write(price11);
document.write("<br>");
document.write(price22)

0
Aki Suihkonen On

Show prices in integer amount of cent units of your currency: after applying e.g. 2% discounts, you can force the values to be handled as integers using bitwise operators:

+var|0;   // '+' handles also objects

Then you need to have a function to show the prices with the decimal point in the correct place.

This is by the way the only way to guarantee prices to add up.