With .toFixed(2)
I always get 2 decimals, even if the number is 2.00
Can I get "2" instead?
Example:
- 2.00 => 2
- 2.05 => 2.05
- 2.053435 => 2.05
- 2.057435 => 2.06
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
+"2.00"
in the console
66.666
rounds to 66.67
to 2 decimal places. If you were expecting 66.66
then that is truncating the number and not rounding and is an entirely different question.
toFixedIfNecessary(value, 10 )
returns a number with at most 10 decimal places and correctly rounded; if your number is small then JavaScript's default method of displaying it is to use scientific notation and your issue is that you want to format the number differently not that it is rounded incorrectly. For formatting, look at some of the later answers to this question such as this answer (and my comment on it).
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
function toFixedIfNecessary(value, dp){
return +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
This is a modification of the answer by @MTO
parseFloat()
is not necessary