5

I have html table with numbers in cells (class "numbers"). Some numbers are whole numbers, others with one decimal number or two decimal numbers.

I would like to make script, that converts all numbers to two decimal format and then put into the code.

e.g.
1 = 1.00
1.0 = 1.00
1.00 = 1.00

Here is my first attemp, that convert one decimal number to two decimal:

var elements = document.getElementsByClassName("numbers");
for (var i = 0, l = elements.length; i < l; i++) {
elements[i].innerHTML = elements[i].innerHTML.replace(/\d{1,2}(\.\d{1})/g, "$&0");
}

2 Answers2

8

Why don't you just parseFloat?

parseFloat(Math.round([elementnumberhere] * 100) / 100).toFixed(2);

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
1

Why not just (+elements[i].innerHTML).toFixed(2) ?

Working demo

letiagoalves
  • 11,224
  • 4
  • 40
  • 66