hongtaesuk
hongtaesuk

Reputation: 31

Java decimal precision question

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

Upvotes: 3

Views: 4191

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533442

Java double and C/C++ double have the same precision. If you want to print 30 decimal places you can use

double d = 1.0/3;
System.out.println("%.30f", d);

However, double doesn't have 30 digits of precision (in any language) and you get a rounding error. If you need 30 decimal places of precision in Java you need to use BigDecimal.

Upvotes: 0

Nivas
Nivas

Reputation: 18344

You can use System.out.printf (doc)

Note, however that this is only for the same purpose as you are using printf in C: for simple debugging/learning.

When you need industrial strength precision, you need BigDecimal

Upvotes: 2

theGame
theGame

Reputation: 393

Simplest solution:

 double roundTwoDecimals(double d) {
            DecimalFormat twoDForm = new DecimalFormat("#.##");
        return Double.valueOf(twoDForm.format(d));
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

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());
    }
}

Upvotes: 9

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

In Java, you could use printf as well, System.out.printf("...", a, b, ...)

Upvotes: 1

Related Questions