Java Scanner nextBigDecimal() Method

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

Definition

In Java, sc.nextBigDecimal() reads the next token and converts it into an exact java.math.BigDecimal. Unlike double, a BigDecimal stores base-10 digits exactly, avoiding binary rounding surprises like 0.1 + 0.2 = 0.30000000000000004.

Like nextDouble(), it follows the scanner's locale() for decimal and grouping symbols, so always set useLocale(Locale.US) for dot decimals.

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.nextBigDecimal(...).

Syntax

Import java.math.BigDecimal and Locale, then read exact decimal tokens.

Java
Scanner sc = new Scanner("19.95 2.50").useLocale(Locale.US);
BigDecimal price = sc.nextBigDecimal();   // 19.95
BigDecimal fee = sc.nextBigDecimal();     // 2.50
CallWhat it does
sc.useLocale(Locale.US).nextBigDecimal()Parses dot decimals into an exact BigDecimal.
sc.hasNextBigDecimal()Checks whether the next token is a valid decimal number first.

BigDecimal preserves trailing zeros in the fractional scale: scanning "2.50" yields a BigDecimal whose toString() prints 2.50, whereas nextDouble() prints 2.5.

Library declarations
Java
// java.util.Scanner
public BigDecimal nextBigDecimal()

Parameters

ParameterDescription
NonenextBigDecimal() takes no parameters.

Return Value

Return ValueDescription
BigDecimalAn immutable exact base-10 decimal value.
Throws InputMismatchExceptionIf the token is invalid, uses a mismatched locale separator, or is NaN/Infinity.
Throws NoSuchElementExceptionIf no tokens remain.
Throws IllegalStateExceptionIf the scanner is closed.

Compare with Similar Methods

Exact decimals vs binary floating-point:

MethodHow it differs
hasNextBigDecimal()Checks decimal validity before reading.
nextDouble()Fast 64-bit float, subject to binary rounding noise.
nextBigInteger()Unlimited whole numbers without decimals.
new BigDecimal(s)Constructs from a dot-decimal String directly.

Java Examples

Example 1 — Sum Line-Item Prices Without Binary Rounding Noise

Compare BigDecimal against double when adding 0.10, 0.20, and 19.95.

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

public class ScannerNextBigDecInvoice {
    public static void main(String[] args) {
        String items = "0.10 0.20 19.95";
        BigDecimal total = BigDecimal.ZERO;
        try (Scanner sc = new Scanner(items).useLocale(Locale.US)) {
            while (sc.hasNextBigDecimal()) {
                total = total.add(sc.nextBigDecimal());
            }
        }
        System.out.println("Exact invoice total: " + total);
    }
}

How It Works

  1. Start from BigDecimal.ZERO. Initializing total as BigDecimal.ZERO gives an exact zero accumulator.
  2. Reassign on every add. Because BigDecimal is immutable, total = total.add(...) stores each updated sum.
  3. Exact cents. Unlike double, adding 0.10 + 0.20 + 19.95 prints clean 20.25.

Example 2 — Scale Preservation and German Comma Parsing

See how nextBigDecimal() keeps trailing zeros like 2.50 and parses comma decimals in Locale.GERMANY.

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

public class ScannerNextBigDecScale {
    public static void main(String[] args) {
        try (Scanner usScanner = new Scanner("2.50").useLocale(Locale.US);
             Scanner deScanner = new Scanner("1.234,50").useLocale(Locale.GERMANY)) {
            BigDecimal us = usScanner.nextBigDecimal();
            BigDecimal de = deScanner.nextBigDecimal();
            System.out.println("US kept scale: " + us + " (scale " + us.scale() + ")");
            System.out.println("DE parsed:     " + de + " (scale " + de.scale() + ")");
        }
    }
}

How It Works

  1. Trailing zero stays. Reading "2.50" retains scale 2, printing 2.50 instead of shrinking to 2.5.
  2. Regional decimal marks. The scanner with Locale.GERMANY reads the dot in "1.234,50" as grouping and the comma as the decimal mark.
  3. Normalized representation. Internally BigDecimal prints with a standard decimal dot as 1234.50.

Example 3 — Reject NaN and Dollar Signs with InputMismatchException

Show that nextBigDecimal() rejects "NaN" and "$15.00" while reading plain "15.00".

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

public class ScannerNextBigDecReject {
    public static void main(String[] args) {
        String text = "NaN $15.00 15.00";
        try (Scanner sc = new Scanner(text).useLocale(Locale.US)) {
            while (sc.hasNext()) {
                try {
                    BigDecimal amount = sc.nextBigDecimal();
                    System.out.println("Amount: " + amount);
                } catch (InputMismatchException e) {
                    System.out.println("Rejected (" + e.getClass().getSimpleName() + "): " + sc.next());
                }
            }
        }
    }
}

How It Works

  1. No NaN support. Even though nextDouble() accepts "NaN", BigDecimal cannot represent NaN, so nextBigDecimal() throws.
  2. No currency symbols. A leading $ fails numeric token matching and must be discarded with sc.next().
  3. Plain decimal works. Once bad tokens are skipped, 15.00 parses cleanly.

Frequently Asked Questions

double uses binary fractions and turns 0.1 + 0.2 into 0.30000000000000004. BigDecimal uses exact base-10 arithmetic, keeping cents accurate.
Yes. Reading "2.50" gives a BigDecimal with scale 2, so printing it displays "2.50".
Yes. Always call sc.useLocale(Locale.US) if your decimal strings use dots, or Locale.GERMANY / Locale.FRANCE if they use commas.
No. Those tokens throw InputMismatchException because BigDecimal only represents finite numbers.
No. BigDecimal tokens are always decimal (base 10).

Next: nextBigInteger()

Read the next token as an arbitrary-size BigInteger.

nextBigInteger() 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.

8 people found this page helpful