Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - replace whole numbers by decimals [duplicate]

Tags:

javascript

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");
}
like image 619
earthandroid Avatar asked Oct 21 '13 15:10

earthandroid


1 Answers

Why don't you just parseFloat?

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

like image 121
Sterling Archer Avatar answered Nov 26 '22 18:11

Sterling Archer