杰瑞科技汇

Java中String与decimal如何转换?

Of course! The term "string decimal" in Java isn't a formal type, but it almost always refers to one of two common scenarios:

Java中String与decimal如何转换?-图1
(图片来源网络,侵删)
  1. Parsing a String that represents a decimal number (e.g., "123.45") into a numeric data type like double or float.
  2. Formatting a numeric type (like double or float) into a String representation with a decimal point (e.g., formatting 45 to "123.45" or "123.4500").

Let's break down both scenarios with detailed explanations and code examples.


Scenario 1: Parsing a String to a Decimal Number (String -> double/float)

This is the process of converting text (a String) into a floating-point number (double or float). This is essential when you get numeric input from a user, a file, or an API.

Key Methods:

  • Double.parseDouble(String s): Converts a String to a primitive double. This is the most common method.
  • Float.parseFloat(String s): Converts a String to a primitive float.
  • Double.valueOf(String s): Converts a String to a Double object (a wrapper class).
  • Float.valueOf(String s): Converts a String to a Float object.

Example: Converting a String to double

public class StringToDoubleExample {
    public static void main(String[] args) {
        String decimalString = "123.456";
        String negativeDecimalString = "-98.76";
        String scientificNotationString = "1.23e4"; // Represents 12300.0
        // Using Double.parseDouble() to get a primitive double
        double number1 = Double.parseDouble(decimalString);
        double number2 = Double.parseDouble(negativeDecimalString);
        double number3 = Double.parseDouble(scientificNotationString);
        System.out.println("String: '" + decimalString + "' -> double: " + number1);
        System.out.println("String: '" + negativeDecimalString + "' -> double: " + number2);
        System.out.println("String: '" + scientificNotationString + "' -> double: " + number3);
        // --- What happens with invalid input? ---
        String invalidString = "hello";
        try {
            Double.parseDouble(invalidString);
        } catch (NumberFormatException e) {
            System.out.println("\nError: Cannot parse the string '" + invalidString + "' to a number.");
            System.out.println("Exception type: " + e.getClass().getSimpleName());
        }
    }
}

Output:

String: '123.456' -> double: 123.456
String: '-98.76' -> double: -98.76
String: '1.23e4' -> double: 12300.0
Error: Cannot parse the string 'hello' to a number.
Exception type: NumberFormatException

Key Takeaway: Always wrap parsing logic in a try-catch block if the input string's format is not guaranteed to be correct. A NumberFormatException will be thrown if the string is not a valid decimal representation.

Java中String与decimal如何转换?-图2
(图片来源网络,侵删)

Scenario 2: Formatting a Decimal Number to a String (double/float -> String)

This is the reverse process: taking a number and converting it into a human-readable String. This is useful for displaying numbers in a user interface, logging, or generating reports.

Key Methods:

  • String.format(): A powerful, versatile method for formatting strings. It uses format specifiers.
  • System.out.printf(): Works like String.format() but prints the result to the console.
  • DecimalFormat: A class from java.text package for more advanced, localized number formatting.
  • BigDecimal.toString(): For high-precision arithmetic, BigDecimal is preferred, and its toString() method gives a precise string representation.

Example 1: Using String.format()

The format specifier for a decimal number is %f.

public class DoubleToStringExample {
    public static void main(String[] args) {
        double price = 19.99;
        double pi = 3.14159265;
        double anotherNumber = 123.0;
        // Basic formatting
        String str1 = String.format("The price is $%f", price);
        System.out.println(str1); // Defaults to 6 decimal places
        // Formatting to a specific number of decimal places
        String str2 = String.format("Pi is approximately %.2f", pi); // 2 decimal places
        System.out.println(str2);
        // Formatting with width and alignment
        String str3 = String.format("|%10.2f|", anotherNumber); // Width of 10, right-aligned
        System.out.println(str3);
        String str4 = String.format("|%-10.2f|", anotherNumber); // Width of 10, left-aligned
        System.out.println(str4);
    }
}

Output:

The price is $19.990000
Pi is approximately 3.14
|     123.00|
|123.00     |

Example 2: Using DecimalFormat

DecimalFormat is excellent for locale-specific formatting (e.g., using a comma as a thousands separator) and repeating patterns.

Java中String与decimal如何转换?-图3
(图片来源网络,侵删)
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class DecimalFormatExample {
    public static void main(String[] args) {
        double largeNumber = 1234567.891;
        // Create a pattern: # means optional digit, 0 means required digit
        DecimalFormat df = new DecimalFormat("#,###.00");
        String formatted1 = df.format(largeNumber);
        System.out.println("Formatted with custom pattern: " + formatted1); // 1,234,567.89
        // Using a predefined locale (e.g., United States)
        NumberFormat usFormat = NumberFormat.getCurrencyInstance(Locale.US);
        String formatted2 = usFormat.format(largeNumber);
        System.out.println("Formatted as US currency: " + formatted2); // $1,234,567.89
        // Using a predefined locale (e.g., Germany)
        NumberFormat deFormat = NumberFormat.getCurrencyInstance(Locale.GERMANY);
        String formatted3 = deFormat.format(largeNumber);
        System.out.println("Formatted as German currency: " + formatted3); // 1.234.567,89 €
    }
}

Output:

Formatted with custom pattern: 1,234,567.89
Formatted as US currency: $1,234,567.89
Formatted as German currency: 1.234.567,89 €

Summary Table: String vs. Decimal in Java

Task Method / Class Example Input Example Output Description
String -> double Double.parseDouble() "123.45" 45 (primitive) Converts a String to a primitive double. Throws NumberFormatException.
String -> Double (Object) Double.valueOf() "123.45" Double object Converts a String to a Double wrapper object.
double -> String String.format() 45 "123.450000" Powerful formatting using specifiers like %.2f.
double -> String (Localized) DecimalFormat or NumberFormat 89 "1,234,567.89" Best for complex patterns, currency, and locale-specific formatting.
High-Precision String -> Number new BigDecimal(String) "123.4500000000" BigDecimal object The safest way to handle financial or exact decimal calculations.

Important Warning: Floating-Point Precision

Be aware that double and float are binary floating-point types and cannot represent all decimal fractions (like 0.1) perfectly. This can lead to small rounding errors.

double a = 0.1 + 0.2;
System.out.println(a); // Prints 0.30000000000000004
// This is why for financial calculations, you should use BigDecimal.
BigDecimal bd1 = new BigDecimal("0.1");
BigDecimal bd2 = new BigDecimal("0.2");
BigDecimal sum = bd1.add(bd2);
System.out.println(sum); // Prints 0.3 exactly
分享:
扫描分享到社交APP
上一篇
下一篇