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.]
num.toLocaleString("en", { minimumFractionDigits: 2 })
If you are using optional chaining you can do it in one line like so:
const addZeroes = num => Number(num).toFixed(Math.max(num.split('.')[1]?.length, 2) || 2)
Without optional chaining you can do it like this:
function addZeroes(num) {
const dec = num.split('.')[1]
const len = dec && dec.length > 2 ? dec.length : 2
return Number(num).toFixed(len)
}
Verbose method/explanation:
function addZeroes(num) {
var value = Number(num); // Convert input string to a number
var parts = num.split("."); // Split the input string into two arrays
// If there is no decimal point or not enough significant figures
if(parts.length == 1 || parts[1].length < 3) {
value = value.toFixed(2); // Set the number to two decimal places
}
return value; // Return the value
}
// If you require the number as a string simply cast back as so
var num = String(value);