7

I need to get a number, knock the last number off and then return it as a number

i.e. given the number 12345, return 1234

is this the best way to do it:

let x = 12345
const y = x.toString().split('').slice(0, -1).join('')
const newNum = Number(y)

also is there a way to not do the const newNum and then just convert it back to a number in the string above?

1
  • 5
    You could just divide the number by 10 and then call Math.floor() Commented Aug 22, 2018 at 14:59

5 Answers 5

23

Here's another way to do it

console.log(
    Math.floor(12345 / 10) // -> 1234
)

Sign up to request clarification or add additional context in comments.

6 Comments

I like this the best
@zfrisch It might, but given how simple the question is, I think it might be a bit too complicated to understand.
It's not complicated? Math.floor(12345 / 10) or 12345 / 10 | 0 will end up with the same result. If someone doesn't understand that, they can look into it. That's how you learn about these things.
@zfrisch I agree, that is how you learn how to do these things, however, I think it is more important understand how the things you are doing work, than just doing it. Since the OP apparently didn't know about Math.floor(12345 / 10), I thought it would be a bit overkill to introduce them to how bitwise operators work and how they convert floating point numbers to signed 32-bit integers . Also, because of that, it won't always give you the same result, it only works upto 2^31 − 1.
@ARatherLongName I'm aware, but I was offering additional information, not an alternative to your answer.
|
5

Easy:

console.log(12345 / 10 ^ 0)

Comments

1

You could refactor the code to this

let x = 12345
const newNum = Number(x.toString().slice(0, -1))
console.log(newNum)

1 Comment

Easily the best because it also works with decimals.
0

Using parseInt() to convert back to number, and substring to get the entire number minus the last digit

return parseInt(x.toString().substring(0, x.toString().length - 1));

Comments

0

Put the number into brackets () to use .slice()

let x = 12345
const newNum = (x).toString().slice(0, -1)
console.log(newNum)
console.log(newNum * 1000)

1 Comment

and now it's a string and not a number

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.