Span decimal point precision In a JSP page I have a number of Span elements. Each of this span element will be floating point numbers.

All these span elements has class "format-decimal-precision":

&lt;span class="format-decimal-precision"&gt;${info.flaot_val}&lt;/span&gt;


I would like to display all this floating point numbers with 3 decimal point precision.

Example: 123.12867 should be displayed as 123.123

var floatFields = $('.format-decimal-precision');
    var iter = floatFields.length;
    var mDecDisplay = 3;

    while(iter--) {
        floatFields[iter].innerHTML=roundNumber($.trim(floatFields[iter].innerHTML),mDecDisplay);
    }

    function roundNumber(num, places) {
        return Math.round(num * Math.pow(10, places)) / Math.pow(10, places);
    }


Though the code is working fine, I would like to know a better program to achieve the same behavior.
Styling and readability

Your indentation is inconsistent. This can lead to developers wrongly assuming code belongs to a different block. I would recommend fixing this for all code.

Your use of whitespace is inconsistent. You sometimes use a space after a comma, you sometimes do not. You sometimes use spaces around operators, you sometimes do not.

Re-inventing the wheel

Your function roundNumber is somewhat re-inventing the wheel. You are basically recreating the toFixed function with a cast back to a number.



function roundNumber(num, places) {
  return Math.round(num * Math.pow(10, places)) / Math.pow(10, places);
}

function roundNumberFixed(num, places) {
  return Number(num).toFixed(places);
}

function roundNumberFixedAsNumber(num, places) {
  return Number(Number( num ).toFixed(places));
}

function test(num, places) {
  console.log("== Testing with", num, "and", places, "==");
  console.log(roundNumber(num, places));
  console.log(roundNumberFixed(num, places) );
  console.log(roundNumberFixedAsNumber(num, places));  
}

var testvalues = [["1.234567", 3],
                  [" 1      ", 2],
                  ["123512.2", 2],
                  ["-55.2121", 5],
                  ["13.223  ", 1]];
console.log("=== Starting tests ===");
for(i in testvalues) {
  test(testvalues[i][0], testvalues[i][1]);
}




You seem to be using jQuery. You can use .each (docs) to loop over all elements in an jQuery object. Similarly, you can use .html (docs) to change the innerHTML of an element.

Termination of loop on referenceError

You use a while loop without a way of terminating it. It actually terminates, because you try to modify the innerHTML of undefined. That's... silly.