Difficulty with Double handling in Java

Asked

Viewed 26 times

-1

I’m getting the value 99999912343000007654329925.7865, declared as Double, but in time to print it I get 99999912343000000000000000.0000.

The error is in or out of that number?

Follow the code:

import java.util.Locale;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws IOException {
        Scanner leitor = new Scanner(System.in);
        Locale.setDefault(Locale.US);
        double X = leitor.nextDouble();
        System.out.println(String.format(" %.4f", X));
        
    }
}
  • The problem is that double has limitations and cannot represent all numbers (in fact, it is an independent characteristic of language, read here). An alternative is to use BigDecimal: https://ideone.com/Q9NzhF

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.