Home Java Scanner Methods nextBigDecimal() Java Scanner nextBigDecimal() Method 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.
Scanner sc = new Scanner("19.95 2.50").useLocale(Locale.US);
BigDecimal price = sc.nextBigDecimal(); // 19.95
BigDecimal fee = sc.nextBigDecimal(); // 2.50 Call What 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.util.Scanner
public BigDecimal nextBigDecimal() Parameters Parameter Description None nextBigDecimal() takes no parameters.
Return Value Return Value Description BigDecimalAn immutable exact base-10 decimal value. Throws InputMismatchException If the token is invalid, uses a mismatched locale separator, or is NaN/Infinity. Throws NoSuchElementException If no tokens remain. Throws IllegalStateException If the scanner is closed.
Compare with Similar Methods Exact decimals vs binary floating-point:
Method How 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 1. Exact invoice sum 2. Trailing zeros and locale 3. Reject NaN and currency Example 1 — Sum Line-Item Prices Without Binary Rounding Noise Compare BigDecimal against double when adding 0.10, 0.20, and 19.95.
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);
}
} Exact invoice total: 20.25 How It Works Start from BigDecimal.ZERO. Initializing total as BigDecimal.ZERO gives an exact zero accumulator.Reassign on every add. Because BigDecimal is immutable, total = total.add(...) stores each updated sum.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.
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() + ")");
}
}
} US kept scale: 2.50 (scale 2)
DE parsed: 1234.50 (scale 2) How It Works Trailing zero stays. Reading "2.50" retains scale 2, printing 2.50 instead of shrinking to 2.5.Regional decimal marks. The scanner with Locale.GERMANY reads the dot in "1.234,50" as grouping and the comma as the decimal mark.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".
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());
}
}
}
}
} Rejected (InputMismatchException): NaN
Rejected (InputMismatchException): $15.00
Amount: 15.00 How It Works No NaN support. Even though nextDouble() accepts "NaN", BigDecimal cannot represent NaN, so nextBigDecimal() throws.No currency symbols. A leading $ fails numeric token matching and must be discarded with sc.next().Plain decimal works. Once bad tokens are skipped, 15.00 parses cleanly.Frequently Asked Questions Why use nextBigDecimal() instead of nextDouble() for money? double uses binary fractions and turns 0.1 + 0.2 into 0.30000000000000004. BigDecimal uses exact base-10 arithmetic, keeping cents accurate.
Does nextBigDecimal() preserve trailing zeros like "2.50"? Yes. Reading "2.50" gives a BigDecimal with scale 2, so printing it displays "2.50".
Does nextBigDecimal() depend on Locale? Yes. Always call sc.useLocale(Locale.US) if your decimal strings use dots, or Locale.GERMANY / Locale.FRANCE if they use commas.
Can nextBigDecimal() read "NaN" or "Infinity"? No. Those tokens throw InputMismatchException because BigDecimal only represents finite numbers.
Can I pass a radix to nextBigDecimal()? No. BigDecimal tokens are always decimal (base 10).
About the author Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion