Reputation: 337
I have this :
i=4.568;
document.write(i.toFixed(2));
output :
4.57
But i don't want to round the last number to 7 , what can i do?
Upvotes: 15
Views: 12764
Reputation: 75327
Use simple math instead;
document.write(Math.floor(i * 100) / 100);
You can stick it in your own function for reuse;
function myToFixed(i, digits) {
var pow = Math.pow(10, digits);
return Math.floor(i * pow) / pow;
}
document.write(myToFixed(i, 2));
Upvotes: 15
Reputation: 887797
Just cut the longer string:
i.toFixed(3).replace(/\.(\d\d)\d?$/, '.$1')
Upvotes: 9
Reputation: 253416
A slightly convoluted approach:
var i=4.568,
iToString = i + '';
i = parseFloat(iToString.match(/\d+\.\d{2}/));
console.log(i);
This effectively takes the variable i
and converts it to a string, and then uses a regex to match the numbers before the decimal point and the two following that decimal point, using parseFloat()
to then convert it back to a number.
References:
Upvotes: 0