Chapter 1: Challenges - Question 8

Can someone explain how you can use modulo to truncate a number to a range that you want? Maybe Iā€™m not understanding what exactly the text means by this.

For example, say we have the integer 2_453_922. Does that mean that I can get the first 3 digits by using the modulo operator? Any help is greatly appreciated!

@rolovee Thanks very much for your question!

The modulo (%) operator is used to get the remainder when doing a division operation between two numbers. For example:

5 % 2 would give you 1, because 2 goes into 5 evenly two times, with a remainder of 1.
8 % 3 would give you 2, because 3 goes into 8 evenly two times, with a remainder of 2. I hope this makes sense.

If your goal is to get the first nth number of digits from a particular number, I would suggest converting that number first into a String, and then use perhaps the prefix() function.

For example

let num = 2453922
var numString = String(num)
var firstThree = numString.prefix(3)  //firstThree = 245

I hope this helps!

All the best.

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.