Numbers and Strings
Turning text into numbers and numbers into text looks trivial until the input has a space in it, the number is in hexadecimal, or the user is in Germany. This page explains the strict and lenient parsers, safe parsing without exceptions, how doubles are printed, hex and binary text, locale-aware formatting and its parsing traps, and what each approach costs.
Contents
Two directions, two kinds of API
Converting between numbers and text happens in two very different settings, and Java has separate APIs for each:
- Machine format is text read or written by programs: configuration files, JSON, CSV, URLs. It uses ASCII digits, a dot as the decimal point and no grouping.
,Integer.parseInt ,Double.parseDouble andtoString work in this format and ignore the user's locale.String.valueOf - Human format is text for people, with grouping separators, currency symbols and the local decimal mark:
in Germany.1.234,50 € andNumberFormat work in this format, and depend on aDecimalFormat .Locale
Mixing them up causes most bugs: writing a file with NumberFormatparseDoubleDouble.toString
| API | Since | Direction | Best for |
|---|---|---|---|
Integer.parseIntLong.parseLong | Java 1.0 | Text to primitive | Strict machine-format integers, any radix 2 to 36 |
Integer.valueOf | Java 1.0 | Text to boxed Integer | When an object is needed; caches -128 to 127 |
Integer.decode | Java 1.2 | Text to Integer | Literals written like Java source: 0x1F010 |
parseUnsignedInttoUnsignedString | Java 8 | Both | Unsigned 32-bit and 64-bit values |
Double.parseDoubleDouble.toString | Java 1.2, 1.0 | Both | Machine-format floating point |
new BigDecimal(String)toPlainString | Java 1.1, 5 | Both | Exact decimals such as money |
Integer.toHexStringHexFormat | Java 1.0, 17 | Number to text | Hex, octal and binary output |
NumberFormatDecimalFormat | Java 1.1 | Both | Human format, with locales and currencies |
NumberFormat.getCompactNumberInstance | Java 12 | Number to text | Short forms such as 2K2M |
The programs below were compiled and run on JDK 21. For String.format
Parsing integers: what parseInt accepts
parseInt
public class Parsing {
public static void main(String[] args) {
int a = Integer.parseInt("42"); // primitive int
Integer b = Integer.valueOf("42"); // boxed Integer
long big = Long.parseLong("9000000000");
System.out.println(a + " " + b + " " + big);
System.out.println("parseInt(\"-17\") = " + Integer.parseInt("-17"));
System.out.println("parseInt(\"+17\") = " + Integer.parseInt("+17"));
System.out.println("parseInt(\"ff\", 16) = " + Integer.parseInt("ff", 16));
System.out.println("parseInt(\"1010\", 2) = " + Integer.parseInt("1010", 2));
System.out.println("parseInt(\"zz\", 36) = " + Integer.parseInt("zz", 36));
System.out.println("decode(\"0x1F\") = " + Integer.decode("0x1F"));
System.out.println("decode(\"010\") = " + Integer.decode("010") + " (octal!)");
System.out.println("parseUnsignedInt(\"4000000000\") = "
+ Integer.parseUnsignedInt("4000000000") + " as a signed int");
System.out.println("parseInt(CharSequence, 4, 8, 10) = "
+ Integer.parseInt("ID: 2026-11", 4, 8, 10));
// Other digit scripts are accepted too: Arabic-Indic digits 4 and 2
System.out.println("parseInt(\"\\u0664\\u0662\") = " + Integer.parseInt("\u0664\u0662"));
for (String bad : new String[] {" 42", "42 ", "4 2", "42.0", "", "3000000000", "1_000",
"1,000", "0x1F"}) {
try {
Integer.parseInt(bad);
System.out.println("parsed \"" + bad + "\"");
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}
}
try {
Integer.parseInt(null);
} catch (NumberFormatException e) {
System.out.println("parseInt(null): NumberFormatException: " + e.getMessage());
}
System.out.println("parseInt(\" 42 \".strip()) = " + Integer.parseInt(" 42 ".strip()));
}
}
Output:
42 42 9000000000
parseInt("-17") = -17
parseInt("+17") = 17
parseInt("ff", 16) = 255
parseInt("1010", 2) = 10
parseInt("zz", 36) = 1295
decode("0x1F") = 31
decode("010") = 8 (octal!)
parseUnsignedInt("4000000000") = -294967296 as a signed int
parseInt(CharSequence, 4, 8, 10) = 2026
parseInt("\u0664\u0662") = 42
NumberFormatException: For input string: " 42"
NumberFormatException: For input string: "42 "
NumberFormatException: For input string: "4 2"
NumberFormatException: For input string: "42.0"
NumberFormatException: For input string: ""
NumberFormatException: For input string: "3000000000"
NumberFormatException: For input string: "1_000"
NumberFormatException: For input string: "1,000"
NumberFormatException: For input string: "0x1F"
parseInt(null): NumberFormatException: Cannot parse null string
parseInt(" 42 ".strip()) = 42
- A leading
or- is allowed. The radix argument reads hex (+ is 255), binary (ff is 10) and any base up to 36, where1010 is 1295.zz understands the prefixes of Java source code:Integer.decode is 31, but0x1F is octal and gives 8. Do not use it for user input with leading zeros.010 succeeds even though the value is aboveparseUnsignedInt("4000000000") ; the bits are stored in anInteger.MAX_VALUE , which prints as -294967296 unless you useint .toUnsignedString- The Java 9 overload
parses part of a string without callingparseInt(CharSequence, begin, end, radix) first; here it read 2026 from index 4 to 8.substring - Digits from other scripts are accepted, because
usesparseInt : two Arabic-Indic digits parsed as 42. Validate with aCharacter.digit check if only ASCII is allowed.[0-9] - Every failure throws
: a space at either end, a space inside, a decimal point, the empty string, a value above 2,147,483,647, underscores and commas (allowed in Java source but not here), and a hex prefix. ANumberFormatException argument also throwsnull , notNumberFormatException .NullPointerException - Stripping first fixes the most common case, input with surrounding spaces.
Parsing without exceptions
When invalid input is normal, such as a form field or a messy CSV column, exceptions are both awkward and slow. The program wraps parsing in an OptionalInt
import java.util.OptionalInt;
public class SafeParse {
static OptionalInt tryParse(String s) {
if (s == null) {
return OptionalInt.empty();
}
try {
return OptionalInt.of(Integer.parseInt(s.strip()));
} catch (NumberFormatException e) {
return OptionalInt.empty();
}
}
// Checks the characters first, so bad input never creates an exception
static OptionalInt tryParseNoThrow(String s) {
if (s == null || s.isEmpty() || s.length() > 11) {
return OptionalInt.empty();
}
long value = 0;
int i = (s.charAt(0) == '-' || s.charAt(0) == '+') ? 1 : 0;
if (i == s.length()) {
return OptionalInt.empty();
}
for (; i < s.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
return OptionalInt.empty();
}
value = value * 10 + (c - '0');
}
value = s.charAt(0) == '-' ? -value : value;
if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
return OptionalInt.empty();
}
return OptionalInt.of((int) value);
}
public static void main(String[] args) {
for (String s : new String[] {"42", " 7 ", "abc", null, "-2147483648", "2147483648"}) {
System.out.printf("%-14s tryParse=%-26s noThrow=%s%n",
s == null ? "null" : "\"" + s + "\"",
tryParse(s), tryParseNoThrow(s));
}
System.out.println("with default: " + tryParse("n/a").orElse(-1));
// Cost of exceptions: 1,000,000 inputs, half of them invalid
String[] inputs = new String[1000000];
for (int i = 0; i < inputs.length; i++) {
inputs[i] = i % 2 == 0 ? Integer.toString(i) : "x" + i;
}
time("parseInt + catch", inputs, true);
time("check chars first", inputs, false);
}
// Best of 3 runs
static void time(String name, String[] inputs, boolean withExceptions) {
long best = Long.MAX_VALUE;
int valid = 0;
for (int run = 0; run < 3; run++) {
valid = 0;
long t0 = System.nanoTime();
for (String s : inputs) {
OptionalInt r = withExceptions ? tryParse(s) : tryParseNoThrow(s);
if (r.isPresent()) {
valid++;
}
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf("%-18s %6.1f ms %,d valid%n", name, best / 1e6, valid);
}
}
Output (timings are a rough comparison, best of 3 runs on a 2-CPU Linux machine, JDK 21):
"42" tryParse=OptionalInt[42] noThrow=OptionalInt[42]
" 7 " tryParse=OptionalInt[7] noThrow=OptionalInt.empty
"abc" tryParse=OptionalInt.empty noThrow=OptionalInt.empty
null tryParse=OptionalInt.empty noThrow=OptionalInt.empty
"-2147483648" tryParse=OptionalInt[-2147483648] noThrow=OptionalInt[-2147483648]
"2147483648" tryParse=OptionalInt.empty noThrow=OptionalInt.empty
with default: -1
parseInt + catch 250.2 ms 500,000 valid
check chars first 14.2 ms 500,000 valid
strips the input, catches the exception and returns an emptytryParse , so callers writeOptionalInt instead of a try block.tryParse(s).orElse(-1) checks every character and the range itself, and never creates an exception. It is stricter: it does not strip, sotryParseNoThrow is rejected, and it accepts only ASCII digits. Both handle the edge values" 7 " and-2147483648 correctly.2147483648- With half the input invalid, the exception-based version was more than twenty times slower. Creating an exception fills in a stack trace, which costs far more than parsing a few digits.
Guava's Ints.tryParseNumberUtils.toInt(s, default)
Floating point: parseDouble and Double.toString
parseDoubleparseIntDouble.toStringtoString
import java.math.BigDecimal;
public class Doubles {
public static void main(String[] args) {
// parseDouble is far more lenient than parseInt
String[] inputs = {"3.14", " 2.5 ", "1e3", "-0", ".5", "5.", "1.5d", "2f",
"0x1p4", "NaN", "-Infinity", "1,5", "1_0"};
for (String s : inputs) {
try {
System.out.printf("parseDouble(%-12s) = %s%n",
"\"" + s + "\"", Double.parseDouble(s));
} catch (NumberFormatException e) {
System.out.printf("parseDouble(%-12s) -> NumberFormatException%n", "\"" + s + "\"");
}
}
// toString gives the shortest text that reads back as the same double
System.out.println("0.1 + 0.2 = " + (0.1 + 0.2));
System.out.println("100.0 = " + 100.0);
System.out.println("1e7, 9999999.0 = " + 1e7 + ", " + 9999999.0);
System.out.println("0.001, 0.0001 = " + 0.001 + ", " + 0.0001);
System.out.println("2e23 = "
+ 2e23 + " (Java 18 and earlier: 1.9999999999999998E23)");
System.out.println("(float) 0.1 = "
+ (float) 0.1 + ", widened to double: " + (double) 0.1f);
System.out.println("round trip = " + (Double.parseDouble(Double.toString(0.1 + 0.2))
== 0.1 + 0.2));
// Plain digits without E notation
System.out.println("BigDecimal.valueOf(1e21).toPlainString() = "
+ BigDecimal.valueOf(1e21).toPlainString());
System.out.println("new BigDecimal(0.1) = " + new BigDecimal(0.1));
System.out.println("String.format(\"%.2f\", 2.675) = " + String.format("%.2f", 2.675));
}
}
Output:
parseDouble("3.14" ) = 3.14
parseDouble(" 2.5 " ) = 2.5
parseDouble("1e3" ) = 1000.0
parseDouble("-0" ) = -0.0
parseDouble(".5" ) = 0.5
parseDouble("5." ) = 5.0
parseDouble("1.5d" ) = 1.5
parseDouble("2f" ) = 2.0
parseDouble("0x1p4" ) = 16.0
parseDouble("NaN" ) = NaN
parseDouble("-Infinity" ) = -Infinity
parseDouble("1,5" ) -> NumberFormatException
parseDouble("1_0" ) -> NumberFormatException
0.1 + 0.2 = 0.30000000000000004
100.0 = 100.0
1e7, 9999999.0 = 1.0E7, 9999999.0
0.001, 0.0001 = 0.001, 1.0E-4
2e23 = 2.0E23 (Java 18 and earlier: 1.9999999999999998E23)
(float) 0.1 = 0.1, widened to double: 0.10000000149011612
round trip = true
BigDecimal.valueOf(1e21).toPlainString() = 1000000000000000000000
new BigDecimal(0.1) = 0.1000000000000000055511151231257827021181583404541015625
String.format("%.2f", 2.675) = 2.68
- Unlike
,parseInt ignores surrounding whitespace, and it accepts exponents, a missing digit before or after the point, a trailingparseDouble ord , hexadecimal floating point (f is 16),0x1p4 andNaN . It still rejects a comma, soInfinity from a European user fails."1,5" prints the shortest decimal that reads back as the sameDouble.toString . That is whydouble prints as 0.30000000000000004: the sum is a different0.1 + 0.2 from 0.3, and the round-trip check confirms the text is exact enough.double- Values of 107 or more, and below 10-3, use E notation:
and1.0E7 , while 9999999.0 and 0.001 do not.1.0E-4 - Java 19 tightened the algorithm (JDK-4511638).
now prints as2e23 ; earlier versions printed2.0E23 .1.9999999999999998E23 - A
widened tofloat shows its real binary value, 0.10000000149011612. For plain digits or exact decimal text, go throughdouble ; seeBigDecimalBigDecimal . gave 2.68, rounding the decimal text half up. TheString.format("%.2f", 2.675) in a later section rounds the same value to 2.67, because it rounds half even and the stored binary value is slightly below 2.675.DecimalFormat
Numbers to text: radix, hex and padding
Converting a number to text is simple for decimal output; the details are in other radixes, negative numbers and fixed widths. The program uses 255 because it is ff
import java.util.HexFormat;
public class ToText {
public static void main(String[] args) {
int n = 255;
System.out.println(String.valueOf(n) + " " + Integer.toString(n) + " " + (n + ""));
System.out.println("hex " + Integer.toHexString(n) + ", octal " + Integer.toOctalString(n)
+ ", binary " + Integer.toBinaryString(n) + ", base 36 " + Integer.toString(n, 36));
// Negative numbers: toHexString shows the two's complement bits, toString keeps the sign
System.out.println("toHexString(-1) = " + Integer.toHexString(-1));
System.out.println("toString(-255, 16) = " + Integer.toString(-255, 16));
System.out.println("toUnsignedString(-1) = " + Integer.toUnsignedString(-1));
// Leading zeros and fixed widths
System.out.println("%08X -> " + String.format("%08X", 48879));
String bits = Integer.toBinaryString(5);
System.out.println("8-bit binary -> " + "0".repeat(8 - bits.length()) + bits);
System.out.println("%05d -> " + String.format("%05d", 42));
// HexFormat (Java 17) for bytes and fixed-width hex
HexFormat hex = HexFormat.of();
System.out.println("HexFormat.toHexDigits((short) 255) = " + hex.toHexDigits((short) 255));
System.out.println("HexFormat.formatHex(bytes) = "
+ HexFormat.ofDelimiter(":").withUpperCase().formatHex(new byte[] {10, -1, 0, 127}));
System.out.println("HexFormat.fromHexDigits(\"ff\") = " + HexFormat.fromHexDigits("ff"));
// char arithmetic is not text conversion
System.out.println("'7' + 1 = " + ('7' + 1) + ", Character.getNumericValue('7') + 1 = "
+ (Character.getNumericValue('7') + 1));
// null: String.valueOf(Object) gives "null", toString() throws
Integer missing = null;
System.out.println("String.valueOf(null Integer) = " + String.valueOf(missing));
try {
System.out.println(missing.toString());
} catch (NullPointerException e) {
System.out.println("missing.toString() -> NullPointerException");
}
}
}
Output:
255 255 255
hex ff, octal 377, binary 11111111, base 36 73
toHexString(-1) = ffffffff
toString(-255, 16) = -ff
toUnsignedString(-1) = 4294967295
%08X -> 0000BEEF
8-bit binary -> 00000101
%05d -> 00042
HexFormat.toHexDigits((short) 255) = 00ff
HexFormat.formatHex(bytes) = 0A:FF:00:7F
HexFormat.fromHexDigits("ff") = 255
'7' + 1 = 56, Character.getNumericValue('7') + 1 = 8
String.valueOf(null Integer) = null
missing.toString() -> NullPointerException
,String.valueOf(n) andInteger.toString(n) give the same text. The compiler turns the concatenation into a call to the same conversion, so the choice is about readability.n + "" istoHexString(-1) : it shows the 32 bits of the two's complement value as unsigned.ffffffff keeps the sign and givesInteger.toString(-255, 16) .-ff reads the same bits as 4294967295.toUnsignedString(-1)- The
methods never add leading zeros.toXxxString pads to 8 hex digits,%08X to 5 decimal digits, and%05d pads binary output."0".repeat , added in Java 17, prints fixed-width hex for each primitive size (HexFormat becomes(short) 255 ), formats byte arrays with delimiters and parses hex back.00ff is 56, because a'7' + 1 in arithmetic is its code, 55.char gives the digit 7.Character.getNumericValue('7') returnsString.valueOf(Object) for a null"null" , while callingInteger on it throws.toString()
Locale-aware formatting and parsing
For people, the same number looks different in each country. The program formats one amount in five locales chosen because they all differ: comma, dot, narrow space and apostrophe grouping, and three currency placements. It then parses localized text, including a value with trailing garbage.
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Locale;
public class Localized {
public static void main(String[] args) throws ParseException {
double amount = 1234567.891;
for (Locale loc : new Locale[] {Locale.US, Locale.GERMANY, Locale.FRANCE,
Locale.forLanguageTag("en-IN"), Locale.forLanguageTag("de-CH")}) {
String plain = NumberFormat.getInstance(loc).format(amount);
String money = NumberFormat.getCurrencyInstance(loc).format(amount);
System.out.printf("%-6s %-16s %s%n", loc.toLanguageTag(), escape(plain), escape(money));
}
NumberFormat compact = NumberFormat.getCompactNumberInstance(Locale.US,
NumberFormat.Style.SHORT);
System.out.println("compact: " + compact.format(1500) + ", " + compact.format(1499)
+ ", " + compact.format(2300000));
DecimalFormat pattern = new DecimalFormat("#,##0.00");
System.out.println("DecimalFormat #,##0.00: " + pattern.format(0.5) + ", "
+ pattern.format(98765.4) + ", " + pattern.format(2.675));
System.out.println("percent: " + NumberFormat.getPercentInstance(Locale.US).format(0.256));
// Parsing localized text back into a number
System.out.println("German \"1.234,5\" -> "
+ NumberFormat.getInstance(Locale.GERMANY).parse("1.234,5"));
System.out.println("US \"1.234,5\" -> "
+ NumberFormat.getInstance(Locale.US).parse("1.234,5"));
// parse stops at the first character it cannot use, without an error
NumberFormat us = NumberFormat.getInstance(Locale.US);
System.out.println("parse(\"12abc\") -> " + us.parse("12abc"));
ParsePosition pos = new ParsePosition(0);
Number n = us.parse("12abc", pos);
System.out.println("with ParsePosition: " + n + ", stopped at index " + pos.getIndex()
+ " of 5 -> reject: " + (pos.getIndex() != 5));
}
// Shows the no-break and narrow no-break spaces some locales use as separators
static String escape(String s) {
return s.replace("\u00A0", "<NBSP>").replace("\u202F", "<NNBSP>").replace("\u2019", "'");
}
}
Output (no-break spaces are shown as <NBSP><NNBSP>
en-US 1,234,567.891 $1,234,567.89
de-DE 1.234.567,891 1.234.567,89<NBSP>€
fr-FR 1<NNBSP>234<NNBSP>567,891 1<NNBSP>234<NNBSP>567,89<NBSP>€
en-IN 1,234,567.891 ₹1,234,567.89
de-CH 1'234'567.891 CHF<NBSP>1'234'567.89
compact: 2K, 1K, 2M
DecimalFormat #,##0.00: 0.50, 98,765.40, 2.67
percent: 26%
German "1.234,5" -> 1234.5
US "1.234,5" -> 1.234
parse("12abc") -> 12
with ParsePosition: 12, stopped at index 2 of 5 -> reject: true
- Germany groups with dots and uses a comma for decimals, France groups with a narrow no-break space (U+202F), and Swiss German uses an apostrophe. India uses the rupee sign. Since Java 9 these rules come from the Unicode CLDR data, so they can change slightly between Java versions.
- Currency formats round to the currency's digits, here 2, and the plain format keeps 3 fraction digits by default.
- Formatted text often contains no-break spaces. Comparing it with a string typed with ordinary spaces fails, which breaks naive unit tests; compare numbers instead of formatted text, or normalize the spaces as shown on the
whitespace page . - Compact formats, added in Java 12, round: 1,500 became
and 1,499 became2K .1K rounds withDecimalFormat by default and works on the exact binary value, so 2.675 became 2.67.HALF_EVEN- The German parser read
as 1234.5, while the US parser read the same text as 1.234, stopping at the comma without complaint.1.234,5 - That is the main trap:
stops at the first character it cannot use and returns what it has, soparse parsed as 12. Pass a12abc and check that it reached the end of the text, as the last line does, to reject such input.ParsePosition
NumberFormatDecimalFormat
How fast is each conversion?
Conversions are cheap one at a time but can dominate when loading large files. The program converts a million values in each direction with the common approaches and reports the best of 3 runs.
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;
import java.util.function.ToLongFunction;
public class ConvertSpeed {
public static void main(String[] args) {
String[] numbers = new String[1000000];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Integer.toString(i * 7);
}
NumberFormat nf = NumberFormat.getInstance(Locale.US);
System.out.println("text -> int, 1,000,000 values:");
time("Integer.parseInt", numbers, Integer::parseInt);
time("Integer.valueOf", numbers, s -> Integer.valueOf(s));
time("Double.parseDouble", numbers, s -> (long) Double.parseDouble(s));
time("NumberFormat.parse", numbers, s -> {
try {
return nf.parse(s).longValue();
} catch (java.text.ParseException e) {
throw new IllegalStateException(e);
}
});
String joined = String.join(" ", numbers);
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
try (Scanner sc = new Scanner(joined)) {
while (sc.hasNextInt()) {
sc.nextInt();
}
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-24s %7.1f ms%n", "one Scanner, nextInt", best / 1e6);
System.out.println("int -> text, 1,000,000 values:");
int[] values = new int[numbers.length];
for (int i = 0; i < values.length; i++) {
values[i] = i * 7;
}
timeInts("Integer.toString", values, v -> Integer.toString(v).length());
timeInts("\"\" + v", values, v -> ("" + v).length());
timeInts("String.format(\"%d\")", values, v -> String.format("%d", v).length());
timeInts("NumberFormat.format", values, v -> nf.format(v).length());
}
static void time(String name, String[] in, ToLongFunction<String> f) {
long best = Long.MAX_VALUE;
long sum = 0;
for (int run = 0; run < 3; run++) {
sum = 0;
long t0 = System.nanoTime();
for (String s : in) {
sum += f.applyAsLong(s);
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-24s %7.1f ms (sum %d)%n", name, best / 1e6, sum);
}
interface IntToLong {
long apply(int v);
}
static void timeInts(String name, int[] in, IntToLong f) {
long best = Long.MAX_VALUE;
long sum = 0;
for (int run = 0; run < 3; run++) {
sum = 0;
long t0 = System.nanoTime();
for (int v : in) {
sum += f.apply(v);
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-24s %7.1f ms (chars %d)%n", name, best / 1e6, sum);
}
}
Output (rough comparison on a 2-CPU Linux machine, JDK 21; times vary between runs):
text -> int, 1,000,000 values:
Integer.parseInt 13.4 ms (sum 3499996500000)
Integer.valueOf 15.3 ms (sum 3499996500000)
Double.parseDouble 46.1 ms (sum 3499996500000)
NumberFormat.parse 94.5 ms (sum 3499996500000)
one Scanner, nextInt 278.3 ms
int -> text, 1,000,000 values:
Integer.toString 17.3 ms (chars 6841267)
"" + v 20.2 ms (chars 6841267)
String.format("%d") 85.8 ms (chars 6841267)
NumberFormat.format 393.9 ms (chars 8698266)
andparseInt took about the same time; boxing small values is cheap.valueOf took two to three times as long, andparseDouble three to seven times as long, because it handles locale symbols and returns a boxedNumberFormat.parse .Number- A single
reading the same million numbers from one text was ten to twenty times slower thanScanner , because it matches every token against a regular expression. Creating a newparseInt for each value is far worse still.Scanner - In the other direction,
andInteger.toString were about equal."" + v was several times slower, because it parses the format pattern on every call, andString.format was the slowest by far.NumberFormat.format
For bulk data, use parseInttoString
Which conversion to use
| Situation | Use |
|---|---|
Text to intlong | Integer.parseInt(s.strip())Long.parseLong |
| Invalid input is expected | A tryParseOptionalInt |
| Hex, binary or another radix | parseInt(s, radix)Integer.toString(n, radix)HexFormat |
Text to double | Double.parseDouble |
| Money or exact decimals | new BigDecimal(s)toPlainString() |
| Number to text for a file or API | String.valueOftoString |
| Fixed width or leading zeros | String.format("%05d", n) |
| Number for people to read | NumberFormat.getInstance(locale)getCurrencyInstance(locale) |
| Parsing what people typed | NumberFormat.parse(text, pos)pos |