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, toString and String.valueOf work in this format and ignore the user's locale.
  • Human format is text for people, with grouping separators, currency symbols and the local decimal mark: 1.234,50 € in Germany. NumberFormat and DecimalFormat work in this format, and depend on a Locale.

Mixing them up causes most bugs: writing a file with NumberFormat and reading it back with parseDouble, or formatting a price for a German user with Double.toString.

Conversion APIs
APISinceDirectionBest for
Integer.parseInt, Long.parseLongJava 1.0Text to primitiveStrict machine-format integers, any radix 2 to 36
Integer.valueOfJava 1.0Text to boxed IntegerWhen an object is needed; caches -128 to 127
Integer.decodeJava 1.2Text to IntegerLiterals written like Java source: 0x1F, 010
parseUnsignedInt, toUnsignedStringJava 8BothUnsigned 32-bit and 64-bit values
Double.parseDouble, Double.toStringJava 1.2, 1.0BothMachine-format floating point
new BigDecimal(String), toPlainStringJava 1.1, 5BothExact decimals such as money
Integer.toHexString, HexFormatJava 1.0, 17Number to textHex, octal and binary output
NumberFormat, DecimalFormatJava 1.1BothHuman format, with locales and currencies
NumberFormat.getCompactNumberInstanceJava 12Number to textShort forms such as 2K and 2M

The programs below were compiled and run on JDK 21. For String.format patterns, see the string formatting page.

Parsing integers: what parseInt accepts

parseInt is strict, which is good for data but surprising for user input. The program parses valid values in several radixes, then a list of inputs that each fail for a different reason.

Java
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:

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 (ff is 255), binary (1010 is 10) and any base up to 36, where zz is 1295.
  • Integer.decode understands the prefixes of Java source code: 0x1F is 31, but 010 is octal and gives 8. Do not use it for user input with leading zeros.
  • parseUnsignedInt("4000000000") succeeds even though the value is above Integer.MAX_VALUE; the bits are stored in an int, which prints as -294967296 unless you use toUnsignedString.
  • The Java 9 overload parseInt(CharSequence, begin, end, radix) parses part of a string without calling substring first; here it read 2026 from index 4 to 8.
  • Digits from other scripts are accepted, because parseInt uses Character.digit: two Arabic-Indic digits parsed as 42. Validate with a [0-9] check if only ASCII is allowed.
  • Every failure throws NumberFormatException: 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. A null argument also throws NumberFormatException, not 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 two ways, then times both on a million inputs of which half are invalid.

Java
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):

Output
"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
  • tryParse strips the input, catches the exception and returns an empty OptionalInt, so callers write tryParse(s).orElse(-1) instead of a try block.
  • tryParseNoThrow checks every character and the range itself, and never creates an exception. It is stricter: it does not strip, so " 7 " is rejected, and it accepts only ASCII digits. Both handle the edge values -2147483648 and 2147483648 correctly.
  • 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.tryParse and Apache Commons' NumberUtils.toInt(s, default) provide the same thing ready-made.

Floating point: parseDouble and Double.toString

parseDouble accepts much more than parseInt, and Double.toString prints binary fractions in ways that surprise people. The inputs cover the accepted syntax, and the outputs show where toString switches to E notation.

Java
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:

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, parseDouble ignores surrounding whitespace, and it accepts exponents, a missing digit before or after the point, a trailing d or f, hexadecimal floating point (0x1p4 is 16), NaN and Infinity. It still rejects a comma, so "1,5" from a European user fails.
  • Double.toString prints the shortest decimal that reads back as the same double. That is why 0.1 + 0.2 prints as 0.30000000000000004: the sum is a different double from 0.3, and the round-trip check confirms the text is exact enough.
  • Values of 107 or more, and below 10-3, use E notation: 1.0E7 and 1.0E-4, while 9999999.0 and 0.001 do not.
  • Java 19 tightened the algorithm (JDK-4511638). 2e23 now prints as 2.0E23; earlier versions printed 1.9999999999999998E23.
  • A float widened to double shows its real binary value, 0.10000000149011612. For plain digits or exact decimal text, go through BigDecimal; see BigDecimal.
  • String.format("%.2f", 2.675) gave 2.68, rounding the decimal text half up. The DecimalFormat 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.

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 in hex and eight ones in binary, and -1 because its bits are all ones.

Java
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:

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), Integer.toString(n) and n + "" give the same text. The compiler turns the concatenation into a call to the same conversion, so the choice is about readability.
  • toHexString(-1) is ffffffff: it shows the 32 bits of the two's complement value as unsigned. Integer.toString(-255, 16) keeps the sign and gives -ff. toUnsignedString(-1) reads the same bits as 4294967295.
  • The toXxxString methods never add leading zeros. %08X pads to 8 hex digits, %05d to 5 decimal digits, and "0".repeat pads binary output.
  • HexFormat, added in Java 17, prints fixed-width hex for each primitive size ((short) 255 becomes 00ff), formats byte arrays with delimiters and parses hex back.
  • '7' + 1 is 56, because a char in arithmetic is its code, 55. Character.getNumericValue('7') gives the digit 7.
  • String.valueOf(Object) returns "null" for a null Integer, while calling toString() on it throws.

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.

Java
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> and narrow no-break spaces as <NNBSP>):

Output
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 2K and 1,499 became 1K.
  • DecimalFormat rounds with HALF_EVEN by default and works on the exact binary value, so 2.675 became 2.67.
  • The German parser read 1.234,5 as 1234.5, while the US parser read the same text as 1.234, stopping at the comma without complaint.
  • That is the main trap: parse stops at the first character it cannot use and returns what it has, so 12abc parsed as 12. Pass a ParsePosition and check that it reached the end of the text, as the last line does, to reject such input.

NumberFormat and DecimalFormat are not thread-safe. Create one per use or per thread rather than sharing a static instance between threads.

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.

Java
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):

Output
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)
  • parseInt and valueOf took about the same time; boxing small values is cheap. parseDouble took two to three times as long, and NumberFormat.parse three to seven times as long, because it handles locale symbols and returns a boxed Number.
  • A single Scanner reading the same million numbers from one text was ten to twenty times slower than parseInt, because it matches every token against a regular expression. Creating a new Scanner for each value is far worse still.
  • In the other direction, Integer.toString and "" + v were about equal. String.format was several times slower, because it parses the format pattern on every call, and NumberFormat.format was the slowest by far.

For bulk data, use parseInt and toString, and keep the locale-aware classes for text that people read.

Which conversion to use

Choosing a conversion
SituationUse
Text to int or long, machine formatInteger.parseInt(s.strip()), Long.parseLong
Invalid input is expectedA tryParse helper returning OptionalInt, ideally checking characters first
Hex, binary or another radixparseInt(s, radix), Integer.toString(n, radix), HexFormat
Text to doubleDouble.parseDouble, remembering it rejects commas
Money or exact decimalsnew BigDecimal(s) and toPlainString()
Number to text for a file or APIString.valueOf or toString
Fixed width or leading zerosString.format("%05d", n)
Number for people to readNumberFormat.getInstance(locale) or getCurrencyInstance(locale)
Parsing what people typedNumberFormat.parse(text, pos), checking pos reached the end