A quick and useful JavaScript function to display numbers with a fixed number of decimal places.
function showAsFloat(num, n) {
var defaultPlaces = 2;
return !isNaN(+num) ? (+num).toFixed(n || defaultPlaces) : num;
}
The default number of places can be set by changing the value of the defaultPlaces variable. In the example above it is set to 2 places.
Calling the function showAsFloat(65.267) would return 65.27
The number of places can be determined when the function is called.
showAsFloat(‘text’,0) will return text so accidental non number scenarios are handled without error.
showAsFloat(65.267,0) will return 65
showAsFloat(65.267,1) will return 65.3
showAsFloat(65.267,2) will return 65.27
Note: The result will be rounded up.