0

I want to limit my numbers to 7 significant figures (I believe this is known as significant digits in American English) with a maximum of 5 decimal places but I am ensure on how to do this.

I am currently using %-7.5f but this always prints 5 decimal places, even if those places aren't significant.

I.e. 3.75 becomes 3.75000

Here's some examples to try and further clarify what I am after:

3097.0 -> 3097

10.39596 -> 10.396

79.6103426 -> 79.61034

I.e. No leading or trailing 0s, 7 significant figures and at most 5 decimal places.

I'm trying to do this as I am working on upgrading an old program written in QBasic and this is how it formats it's floating point numbers when they are displayed. I want my Java code to output the numbers this way simply to make it easier to compare the results.

Lerp
  • 2,957
  • 3
  • 24
  • 43

3 Answers3

2

I suggest to use DecimalFormat for this purpose

new DecimalFormat("#.#####").format(d)

this pattern limits fractional part to max 5 digits

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
2

You can use DecimalFormat for this

    double value1 = 10.39596;
    double value2 = 79.6103426;
    DecimalFormat df = new DecimalFormat("#.#####");
    System.out.print(df.format(value1));
    System.out.print(df.format(value2));
Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
1

What about

DecimalFormat format = new DecimalFormat("#.#####");
System.out.println(format.format(79.6103426));
Reimeus
  • 158,255
  • 15
  • 216
  • 276