I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1
Is this what you mean?
function showAsFloat(num, n){
return !isNaN(+num) ? (+num).toFixed(n || 2) : num;
}
document.querySelector('#result').textContent =
[
'command | result',
'-----------------------------------------------',
'showAsFloat(1); | ' + showAsFloat(1),
'showAsFloat(1.314); | ' + showAsFloat(1.314),
'showAsFloat(\'notanumber\') | ' + showAsFloat('notanumber'),
'showAsFloat(\'23.44567\', 3) | ' + showAsFloat('23.44567', 3),
'showAsFloat(2456198, 5) | ' + showAsFloat('2456198', 5),
'showAsFloat(0); | ' + showAsFloat(0)
].join('\n');