With .toFixed(2)
I always get 2 decimals, even if the number is 2.00
Can I get "2" instead?
Example:
function toFixedIfNecessary( value, dp ){
return +parseFloat(value).toFixed( dp );
}
console.log( toFixedIfNecessary( 1.999, 2 )); // 2
console.log( toFixedIfNecessary( 2, 2 )); // 2
console.log( toFixedIfNecessary( 2.1, 2 )); // 2.1
console.log( toFixedIfNecessary( 2.05, 2 )); // 2.05
console.log( toFixedIfNecessary( 2.05342, 2 )); // 2.05
console.log( toFixedIfNecessary( 2.04999, 2 )); // 2.05
console.log( toFixedIfNecessary( 2.04499, 2 )); // 2.04
console.log( toFixedIfNecessary( 2.053435, 2 )); // 2.05
console.log( toFixedIfNecessary( 2.057435, 2 )); // 2.06
You can use Math.round()
:
var number = 2.005;
var number2 = 2.558934;
var number3 = 1.005;
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
console.log(round(number, 2)) // > 2.01
console.log(round(number2, 2)) // > 2.56
console.log(round(number3, 2)) // > 1.01
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