Yesterday I was trying to figure out how to format numbers such as 71.75, 99.8, and 111.699999999999 as n.nn strings. In VBScript, you can do this:
strFormatted = FormatNumber(dblVar, 2)
JavaScript doesn’t seem to have anything like this, so I ended up doing the following. Is there a neater way?
var strFormatted = Math.round(floatVar * 100).toString(); strFormatted = strFormatted.substr(0, strFormatted.length - 2) + '.' + strFormatted.substr(strFormatted.length - 2, 2);
Notes:
1. In real life, there is no break in that last line.
2. I realize that for values of floatVar less than 1, I won’t get a leading zero. I didn’t have to worry about that for the demo page I was building.