0

I am trying to divide a 19 digit number by 100, i.e. 19 digit number/100, in java. It can be divisible using long data type but I'm not getting the full value as 17 digits and a decimal point followed by another 2 digits. Instead, I'm only getting 17 digits as it was a long data type so I need that digit like mathematical expression.

long cardValue = ("1234567891234567891");

long divide = (cardValue/100);

System.out.println(divide);

Output: 12345678912345678

I need output as 12345678912345678.91

Mureinik
  • 297,002
  • 52
  • 306
  • 350

4 Answers4

3

longs are large integers, and when you divide one by another you use integer division, which omits everything right of the decimal point.

You could use a BigDecimal instead:

BigDecimal divide = new BigDecimal(String.valueOf(cardValue)).divide(new BigDecimal(100));
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Firstly, you are doing integer division, and then expecting a decimal value. In Java, 1234 / 10 results in 123, and not 123.4. If you want a decimal result, make one of the values decimal, i.e., 1234.0 / 10 or 1234 / 10.0. This will yield 123.4

As of your problem, since the number is very large, using BigDecimal is a better idea (not BigInteger, as it will again perform integer division, while you want a decimal result). So, try

BigDecimal b = new BigDecimal("1234567891234567891");
BigDecimal res = b.divide(new BigDecimal("100"));

Or you can do a one-liner as

new BigDecimal("1234567891234567891").divide(new BigDecimal("100"))

In first, res = 12345678912345678.91, and the other will also result in the same. Note : Although BigInteger and BigDecimal are all included in java.math package, but if it raises an error, import it by using import java.math.BigDecimal;

Swati Srivastava
  • 1,102
  • 1
  • 12
  • 18
0

Integer and long don't have decimal point. Instead, use double.

double a = 123456789.00
double answer = (a/100.00)

Refer primitive data types in java.

If you want to get the string and want to dive, then use parseDouble() method to convert it to double. After this step perform division.

Anand Raja
  • 2,676
  • 1
  • 30
  • 35
  • Next question [is-floating-point-math-broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Scary Wombat Feb 12 '20 at 06:50
0

The divide variable is long type, that means no decimal fractions, just integer values. If you use double, you can obtain decimals, but that type don't have the precision you need in this case because it gives up to 15 significant numbers.

Your only solution is to use BigDecimal class. You can obtain whatever digit numbers you want. We used it for Banks and accounting applications, and is easy to understand how to work with it.

HTH

user6656519
  • 101
  • 3