0
double a=816992306.6297043221;
System.out.println("a="+a);

The problem with this is that the number is too large for double, and it gives the following output:

a=8.169923062970433E7

When I decrease the number, the result gets displayed correctly. What is the efficient solution for this problem?

BUY
  • 705
  • 1
  • 11
  • 30
  • 4
    The number is not too large for double. It's just shown in the scientific notation. There is nothing wrong with that, it's intended behavior. – Ben May 30 '18 at 12:28
  • Possible duplicate of [Double vs. BigDecimal?](https://stackoverflow.com/questions/3413448/double-vs-bigdecimal) – Patrick Parker May 30 '18 at 12:28
  • With the answer by Davide Lorenzo MARINO in mind it is indeed correct though that you are loosing precision on the last 3 decimal places. – Ben May 30 '18 at 12:32

2 Answers2

2

You can use a BigDecimal number instead of double:

Immutable, arbitrary-precision signed decimal numbers.

BigDecimal can represent any number with the choosen precision.

Double has limits on maximum and minimum values and on precision.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

I think it is a precision problem.

https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

You can check this link out for learning about format.

You can use DecimalFormat Class

double d1 = 3.14159;
double d2 = 1.235;

DecimalFormat format = new DecimalFormat("#.##");

double roundedD1 = format.format(d1); // 3.14
double roundedD2 = format.format(d2); // 1.24

If you want to set the precision during runtime.

format.setMaximumFractionDigits(precision);
BUY
  • 705
  • 1
  • 11
  • 30