How to represent currency in Java

1 Answer

0 votes
/**---------------------------------------------------------
  Description:
    Demonstrates how to represent and display currency
    values in Java using BigDecimal and NumberFormat.
---------------------------------------------------------*/

import java.math.BigDecimal;
import java.text.NumberFormat;

public class CurrencyExample {

    public static void main(String[] args) {

        // Create currency formatter for US dollars
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        
        // Price and tax rate
        BigDecimal price = new BigDecimal("199.99");
        BigDecimal taxRate = new BigDecimal("0.17"); // 17%

        // Calculate tax and total
        BigDecimal taxAmount = price.multiply(taxRate);
        BigDecimal total = price.add(taxAmount);

        // Output with $ and % signs
        System.out.println("Price: " + currency.format(price));
        System.out.println("Tax Rate: 17%");
        System.out.println("Tax Amount: " + currency.format(taxAmount));
        System.out.println("Total: " + currency.format(total));
    }
}



/*
run:

Price: $199.99
Tax Rate: 17%
Tax Amount: $34.00
Total: $233.99

*/

 



answered 3 hours ago by avibootz
...