Get first N digits of a number

java, numbers

Solution

The following might do what you want, if what you want to do is what I think you want to do:

long n = 2432902008176640000L; // original number
while (n > 9999) {
   // while "more than 4 digits", "throw out last digit"
   n = n / 10;
}
// now, n = 2432

And a demo.

Notes:

A `long` can only represent values as large as 9223372036854775807 (which is only about 4 times as large as the number given) before it will overflow. If dealing with larger numbers you'll need to switch to BigInteger or similar. The same technique can be used, updated for syntax differences.

As fge pointed out, this won't work as it is written over negative numbers; this can be addressed by either changing the condition (i.e. `n < -9999`) or first obtaining the absolute value of n (and then reverting the operation at the end).

As done in yinqiwen's answer, `n > 9999` can be replaced with `n >= (long)Math.pow(10, N)` (preferably using a temporary variable), where N represents the number of decimal digits.

Problem

I'm writing a small program that displays the factorial of a number. When I enter the number 20 I got the number 2432902008176640000 as result. How can I limit a decimal number in Java. For example the number 2432902008176640000 should be 2432 (limit 4). Thanks in advance.

Original source

Related problems