To format a number as currency in Java, you can use the NumberFormat
class of the java.text
package. The NumberFormat
class provides methods for formatting and parsing numbers, including currency values.
Here's an example of how to use the NumberFormat
class to format a number as currency:
import java.text.NumberFormat; import java.util.Locale; public class Main { public static void main(String[] args) { double amount = 123.45; // Get a NumberFormat instance for formatting currency values NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US); // Format the amount as currency String formattedAmount = currencyFormat.format(amount); System.out.println(formattedAmount); // prints "$123.45" } }Source:wwl.wautturi.com
This code uses the getCurrencyInstance()
method of the NumberFormat
class to get a NumberFormat
instance that is configured for formatting currency values. The format()
method of the NumberFormat
object is then used to format the amount as currency.
You can specify a Locale
object as an argument to the getCurrencyInstance()
method to specify the locale for which the currency format is desired. In this example, the Locale.US
locale is used, which specifies the US currency format (a dollar sign followed by the amount).