Reputation: 794
I have some case about toFixed(2);
var abc = 20;
var xyz = 20;
var sss = ((parseInt(abc) / parseInt(xyz));
if (!isNaN(sss))
{
console.log(sss);
}
output: 1
var abc = 20;
var xyz = 19;
var sss = (parseInt(abc) / parseInt(xyz));
if (!isNaN(sss))
{
console.log(sss.toFixed(2));
}
output: 1.05
var abc = 20;
var xyz = 20;
var sss = ((parseInt(abc) / parseInt(xyz));
if (!isNaN(sss))
{
console.log(sss.toFixed(2));
}
output: 1.00
The problem is that I want to avoid the trailing digits if the result is an integer. I only want the toFixed(2)
format when the result is a float. How can I do that ?
Example:
var num = (1.01).toFixed(2)
console.log( num) //output ok 1.01
// But When
var num = (1.00).toFixed(2)
console.log( num) //expected output 1
I having the issue will you guys please help.
Upvotes: 2
Views: 293
Reputation: 371019
Check with Number.isInteger
:
const show = (a, b) => {
const div = a / b;
if (Number.isNaN(div)) {
return;
}
const toDisplay = Number.isInteger(div) ? div : div.toFixed(2);
console.log(toDisplay);
};
show(19, 20);
show(20, 20);
show(22, 20);
Upvotes: 3