5

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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
user2773145
  • 381
  • 2
  • 4
  • 6

6 Answers6

9

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:

  1. 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.

  2. 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).

  3. 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.

user2864740
  • 60,010
  • 15
  • 145
  • 220
3

Try this, may help:

Long n = 2432902008176640000;
String num = String.valueOf(n);
num = num.subString(0, 4);
n = Long.valueOf(num);
earthmover
  • 4,395
  • 10
  • 43
  • 74
3

Replace N by the limit.

long v = 2432902008176640000L; 
long x = (long) Math.pow(10, N);

while(v >= x)
{
   v /= 10;
}
yinqiwen
  • 604
  • 6
  • 6
3

Some of the previous answers with loops are O(n) time complexity. Here's a solution for constant time complexity:

long num = 2432902008176640000L;
int n = 4;
long first_n = (long) (num / Math.pow(10, Math.floor(Math.log10(num)) - n + 1));
dom
  • 377
  • 3
  • 3
2

I am assuming you mean factorial of a number. Just convert the number into a string and use substring method to get first 4 digits only. fact is the factorial value

    String result_4_str=(fact+"").substring(0, 4);
    long result_4 = Long.parseLong(result_4_str);
    System.out.println(result_4);
Pratik Roy
  • 724
  • 1
  • 5
  • 21
1

You can try

long number = 2432902008176640000L ;
String numberStr = String.valueOf(number);      
if(numberStr.length()>=4){
    System.out.println(numberStr.substring(0, 4));      
}
Zeeshan
  • 11,851
  • 21
  • 73
  • 98