简体   繁体   中英

Java: Display float with precision of 30

I'm trying to calculate PI with some algorithms, but the main thing is to display it with precision of 30. I tried to output a string with format etc. But it seems that maximum precision of double is 15. Is there any class or some method to help me with this ?

I've already tried:

public class Challenge6PI {

    public static void main(String[] args){

        System.out.format( "%.30f",
                Math.log(Math.pow(640320, 3) + 744) / Math.sqrt(163));
    }
}

While the JDK has BigDecimal , unfortunately you have no .sqrt() on it.

Which means your best bet is to use apfloat :

final Apfloat f1 = new Apfloat(640320);
final Apfloat f2 = ApfloatMath.pow(f1, 3L);
final Apfloat f3 = f2.add(new Apfloat(744));
final Apfloat f4 = ApfloatMath.sqrt(new Apfloat(163), 1000L);
final Apfloat ret = ApfloatMath.log(f3.divide(f4));

System.out.println(ApfloatMath.round(ret, 30L, RoundingMode.HALF_DOWN));

You have a shorter way for pi, though ;)

System.out.println(ApfloatMath.pi(30L));

I guess Float does not supports that much precision. You may use BigDecimal for that.

double doesn't have that much precision. Have a look at how the double type is implemented . For arbitrary precision have a look at BigDecimal

For example:

BigDecimal bd = new BigDecimal(22.0/7.0);
df.setMaximumFractionDigits(30);
System.out.println(df.format(bd));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM