1

How can I verify how many decimals a number has in Java?

I need to calculate PI to a certain number of decimal, and I want to know how I can stop my loop when I reach the desired decimals number?

Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73
user2997779
  • 297
  • 1
  • 16

4 Answers4

1

You can't check the number of decimals on a double directly, but you can convert it to a String using String str = number + ""; and then check str.length.

Warlord
  • 2,798
  • 16
  • 21
0

If you use BigDecimal for your calculation you could set the scale to the desired value.

nitnamby
  • 404
  • 2
  • 8
0

If you only need a small precision e.g. 15 decimal places, you can use double for that. To specify the number of digits you could use Math.pow(10, -decimalPlaces) to calculate the smallest allowed deviation.

Tesseract
  • 8,049
  • 2
  • 20
  • 37
0

1) you firstly convert it to string

2)Then take a substring from '.' to end

3) Thenget the length of this substring

TruePS
  • 493
  • 2
  • 12
  • 33