Java Scanner nextDouble() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Scanner

Definition

In Java, sc.nextDouble() reads the next token and converts it into a 64-bit IEEE 754 double. It accepts plain decimals like 3.5, whole numbers like 10 (returned as 10.0), scientific notation like 1.5E3, and special tokens NaN and Infinity.

Locale matters: nextDouble() expects either a dot (3.5) or a comma (3,5) as the decimal separator depending on the scanner's locale().

An instance method of java.util.Scanner, available since Java 5 (JDK 1.5). A Scanner reads from any source (System.in for keyboard, a String, or a file) with identical parsing logic; pass the source to new Scanner(...) after import java.util.Scanner; and call sc.nextDouble(...).

Always specify Locale.US for dot decimals.

A scanner starts with the JVM's default locale. On a German or French machine, new Scanner("3.5").nextDouble() fails with InputMismatchException unless you call sc.useLocale(Locale.US) first.

Syntax

Chain .useLocale(Locale.US) when parsing dot-decimal inputs before calling nextDouble().

Java
Scanner sc = new Scanner("19.95 10").useLocale(Locale.US);
double price = sc.nextDouble();   // 19.95
double tax = sc.nextDouble();     // 10.0
CallWhat it does
sc.useLocale(Locale.US).nextDouble()Parses dot-decimal input reliably regardless of OS region.
sc.hasNextDouble()Checks whether the next token is a valid double in the current locale.
sc.nextDouble()Parses a decimal number, exponent, or NaN/Infinity.

Unlike integer methods, nextDouble() has no radix overload—floating-point scanner tokens are always base 10. For exact currency calculations where binary rounding like 0.1 + 0.2 causes drift, prefer nextBigDecimal().

Library declarations
Java
// java.util.Scanner
public double nextDouble()

Parameters

ParameterDescription
NonenextDouble() takes no parameters.

Return Value

Return ValueDescription
doubleThe parsed 64-bit floating-point number.
Throws InputMismatchExceptionIf the token does not match the current locale's decimal format.
Throws NoSuchElementExceptionIf no more tokens are left.
Throws IllegalStateExceptionIf the scanner has been closed.

Compare with Similar Methods

Decimal-number options in Scanner:

MethodHow it differs
hasNextDouble()Tests decimal format before reading.
nextFloat()32-bit float with lower precision.
nextBigDecimal()Exact base-10 arithmetic for prices and money.
useLocale(loc)Selects dot vs comma decimal rules.

Java Examples

Example 1 — Compute the Average of Decimal Exam Marks

Use Locale.US so dot-separated decimals work consistently everywhere, then compute the average.

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

public class ScannerNextDoubleMarks {
    public static void main(String[] args) {
        String marks = "88.5 91.0 79.5";
        double total = 0.0;
        int count = 0;
        try (Scanner sc = new Scanner(marks).useLocale(Locale.US)) {
            while (sc.hasNextDouble()) {
                total += sc.nextDouble();
                count++;
            }
        }
        System.out.println("Total: " + total);
        System.out.println("Average: " + (total / count));
    }
}

How It Works

  1. Dot decimals locked in. Calling useLocale(Locale.US) guarantees "88.5" and "79.5" parse properly on any computer.
  2. Sum and count together. Each loop iteration consumes one decimal and increments count until all three marks are totaled to 259.0.
  3. Full double division. Dividing 259.0 by 3 prints the exact IEEE 754 double quotient 86.33333333333333.

Example 2 — Parse US and German Formatted Numbers

Switch a scanner's locale from Locale.US to Locale.GERMANY and watch how comma decimals behave.

Java
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;

public class ScannerNextDoubleLocales {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("3,5 1.234,5").useLocale(Locale.US)) {
            try {
                System.out.println(sc.nextDouble());
            } catch (InputMismatchException e) {
                System.out.println("US rejected 3,5: " + e.getClass().getSimpleName());
            }
            sc.useLocale(Locale.GERMANY);
            System.out.println("DE 3,5 -> " + sc.nextDouble());
            System.out.println("DE 1.234,5 -> " + sc.nextDouble());
        }
    }
}

How It Works

  1. US rejects decimal comma. Under Locale.US, "3,5" has only one digit after the comma (not three for grouping), so nextDouble() throws without advancing.
  2. Switch locale mid-stream. Calling useLocale(Locale.GERMANY) updates the parser rules immediately without discarding "3,5".
  3. Java always prints dots. Even after reading German notation "1.234,5", Java's Double.toString prints 1234.5.

Example 3 — Parse Scientific Notation, NaN, and Infinity

Verify that nextDouble() understands exponential notation and IEEE special floating-point words.

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

public class ScannerNextDoubleSpecial {
    public static void main(String[] args) {
        String tokens = "1.5E3 2.50 NaN -Infinity";
        try (Scanner sc = new Scanner(tokens).useLocale(Locale.US)) {
            while (sc.hasNextDouble()) {
                System.out.println(sc.nextDouble());
            }
        }
    }
}

How It Works

  1. Exponent expansion. 1.5E3 means 1.5 times 1000, which prints in standard decimal notation as 1500.0.
  2. Trailing zeros normalize. "2.50" stores the numeric value 2.5 and drops the extra trailing zero when printed.
  3. Special IEEE tokens. Both "NaN" and "-Infinity" match hasNextDouble() and parse into their double constants.

Frequently Asked Questions

If your system default locale uses commas for decimals (such as German or French), Scanner expects 3,5 instead of 3.5. Call sc.useLocale(Locale.US) before reading.
No. Floating-point inputs in Scanner are always parsed in base 10.
nextDouble() stops before the newline character, leaving it in the buffer. Call sc.nextLine() once to discard the leftover newline before reading the next real line.
Yes. "10" parses as the double 10.0.
Prefer nextBigDecimal() for exact money math so binary floating-point rounding (like 0.1 + 0.2 = 0.30000000000000004) never alters cents.

Next: nextFloat()

Read the next token as a float.

nextFloat() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful