Reputation: 437
How can I remove the last digits of a number (not string) using JavaScript.
Example:
Input : 2121.1124
Output : 2121.112
I google it a lot. But everywhere I found remove string. How can I do it?
This is the code for remove last char of a string.
var str = "stackoverflow";
str = str.substring(0, str.length - 1);
console.log(str);
How can I do it for a digit(not string) ?
Upvotes: 2
Views: 4974
Reputation: 521
Use number.toFixed(amountOfDecimals);
to round, where amountOfDecimals
is 3.
Use Math.floor( number * Math.pow(10, amountOfDecimals) ) / Math.pow(10, amountOfDecimals);
to avoid rounding. So, for 3 decimal places, that becomes Math.floor( 2121.1124 * 1000 ) / 1000;
Not sure which one you need.
Edited to reflect h2ooooooo's suggestion below.
Upvotes: 6
Reputation: 20574
output= parseInt(input*1000)/1000
the parseInt(input*1000) will remove all nums after the third after the decimal.
Upvotes: 0
Reputation: 647
You can display the decimal numbers using toFixed()
like the following:
parseFloat(2121.1124).toFixed(3)
this will return 2121.112
Upvotes: 0