Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java decimal precision question

Tags:

java

I have a problem which I have to print with long decimal places. such as 1/3 = 0.33333333333333333333333333333333333333 (very very long) when using C, we can use printf("%.30f", a); but I don't know what to do using Java

like image 807
hongtaesuk Avatar asked Apr 21 '26 01:04

hongtaesuk


1 Answers

You won't get that many decimal places of precision in IEEE754 binary floating point numbers in either C or Java. Your best bet would be to use BigDecimal and perform the arithmetic with a particular precision. For example:

import java.math.*;

public class Test {
    public static void main(String[] args) throws Exception {
        MathContext context = new MathContext(30);
        BigDecimal result = BigDecimal.ONE.divide(new BigDecimal(3), context);
        System.out.println(result.toPlainString());
    }
}
like image 161
Jon Skeet Avatar answered Apr 22 '26 13:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!