generally, to fix the number in javascript we write the toFixed(2) function. I want to make a function for numbers when a number has a decimal like 12.326252 it will show 12.33 and when it has no decimal like 123 it will show 123, not 123.00.
means if decimal when adding auto .toFixed(2) else not.
How I active the goal
I wrote the code but it not working, please help to fix this bug.
number = 20.526
function check(number) {
if (number == Math.floor(number)) {
//console.log(number)
return number;
} else {
//console.log(number.toFixed(2))
return number.toFixed(2);
}
}
check(number);
Hi @wawane7256, note that toFixed() is a formatting method and returns a string not a number; if this is what you want, you might use a regular expression to remove the .00 suffix:
number.toFixed(2).replace(/\.00$/, '')
If you want an actual number though just convert it using Number() and you won’t get the trailing zero decimals:
Number(number.toFixed(2))
Or another way without intermediary string conversion:
Please help me, how to achieve the goal, this is the below code pls fix it for me… till I didn’t make this correct
function number(number) {
if (number == Math.floor(number)) {
return number;
} else {
return Number(Number(number).toFixed(2).replace(/\.00$/, ""));
}
};
console.log(number(10+10)) // working fine
console.log(number(10+"10")) // not working
console.log(number("10"+10)) // not working
console.log(number(10+number("10"))) // not working