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) ?
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) ?
Share Improve this question edited May 14, 2014 at 8:41 user3610762 asked May 14, 2014 at 8:34 user3610762user3610762 4371 gold badge5 silver badges14 bronze badges 4- 1 youre sure you dont want to round ? – john Smith Commented May 14, 2014 at 8:36
- convert it to a string than back to a float if you can do it with a string – edi9999 Commented May 14, 2014 at 8:36
- 1 But what wrong with strings? Truncating a string will give you exactly what you want. Why do you need only number operations? – Gino Pane Commented May 14, 2014 at 8:37
-
You are dealing with a float, why the heck are you looking for substring?
Number.prototype.toFixed()
is the right way. See developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – user1659862 Commented May 14, 2014 at 8:43
3 Answers
Reset to default 6Use 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 bees Math.floor( 2121.1124 * 1000 ) / 1000;
Not sure which one you need.
Edited to reflect h2ooooooo's suggestion below.
You can display the decimal numbers using toFixed()
like the following:
parseFloat(2121.1124).toFixed(3)
this will return 2121.112
output= parseInt(input*1000)/1000
How does it work ?
the parseInt(input*1000) will remove all nums after the third after the decimal.