user3610762
user3610762

Reputation: 437

Remove the last digits of a number (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) ?

Upvotes: 2

Views: 4974

Answers (3)

roobeedeedada
roobeedeedada

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

edi9999
edi9999

Reputation: 20574

output= parseInt(input*1000)/1000

How does it work ?

the parseInt(input*1000) will remove all nums after the third after the decimal.

Upvotes: 0

Vinoth
Vinoth

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

Related Questions