I need to add zeroes, so that each number has at least two decimals, but without rounding. So for example:
5 --> 5.00 5.1 --> 5.10 5.11 --> 5.11 (no change) 5.111 --> 5.111 (no change) 5.1111 --> 5.1111 (no change)
My function is missing an IF to check for less than two decimal places:
function addZeroes( num ) { var num = Number(num); if ( //idk ) { num = num.toFixed(2); } return num; }
Thanks!
Posting an alternative answer, in addition to the two below. (Keep in mind that I'm no expert and this is just for text inputs, not for parsing complex values like colors that could have floating point issues, etc.)
function addZeroes( value ) { //set everything to at least two decimals; removs 3+ zero decimasl, keep non-zero decimals var new_value = value*1; //removes trailing zeros new_value = new_value+''; //casts it to string pos = new_value.indexOf('.'); if (pos==-1) new_value = new_value + '.00'; else { var integer = new_value.substring(0,pos); var decimals = new_value.substring(pos+1); while(decimals.length<2) decimals=decimals+'0'; new_value = integer+'.'+decimals; } return new_value; }
[This is not a duplicate question. The question you linked assumes "knowing that they have at least 1 decimal." Decimal points cannot be assumed in text inputs, and this was making errors.]
Description. toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.
Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.
To add two decimal numbers, first check if they have the same number of digits to the right of the decimal point. If they don't, add zeros to the right of one of the numbers until they do. Then, write one number on top of the other, lining up the decimal points vertically.
Here you go:
function addZeroes(num) { // Convert input string to a number and store as a variable. var value = Number(num); // Split the input string into two arrays containing integers/decimals var res = num.split("."); // If there is no decimal point or only one decimal place found. if(res.length == 1 || res[1].length < 3) { // Set the number to two decimal places value = value.toFixed(2); } // Return updated or original number. return value; } // If you require the number as a string simply cast back as so var num = String(value);
See updated fiddle for demonstration.
edit: Since I first answered this, javascript and I have progressed, here is an updated solution using es6, but following the same idea:
function addZeroes(num) { const dec = num.split('.')[1] const len = dec && dec.length > 2 ? dec.length : 2 return Number(num).toFixed(len) }
Updated fiddle
Maybe use .toLocaleString()
:
var num = 5.1; var numWithZeroes = num.toLocaleString("en",{useGrouping: false,minimumFractionDigits: 2}); console.log(numWithZeroes);
As a function/demo:
function addZeroes(num) { return num.toLocaleString("en", {useGrouping: false, minimumFractionDigits: 2}) } console.log('before after correct'); console.log('5 ->', addZeroes(5) , ' --> 5.00'); console.log('5.1 ->', addZeroes(5.1) , ' --> 5.10'); console.log('5.11 ->', addZeroes(5.11) , ' --> 5.11 (no change)'); console.log('5.111 ->', addZeroes(5.111) , ' --> 5.111 (no change)'); console.log('5.1111 ->', addZeroes(5.1111) , '--> 5.1111 (no change)'); console.log('-5 ->', addZeroes(-5) , ' --> -5.00');
And if you must use .toFixed()
, here's a one-liner:
var num = 5.1; var numWithZeroes = num.toFixed(Math.max(((num+'').split(".")[1]||"").length, 2)); console.log(numWithZeroes);
Or, again, as a function/demo:
function addZeroes(num) { return num.toFixed(Math.max(((num+'').split(".")[1]||"").length, 2)); } console.log('before after correct'); console.log('5 ->', addZeroes(5) , ' --> 5.00'); console.log('5.1 ->', addZeroes(5.1) , ' --> 5.10'); console.log('5.11 ->', addZeroes(5.11) , ' --> 5.11 (no change)'); console.log('5.111 ->', addZeroes(5.111) , ' --> 5.111 (no change)'); console.log('5.1111 ->', addZeroes(5.1111) , '--> 5.1111 (no change)'); console.log('-5 ->', addZeroes(-5) , ' --> -5.00');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With