提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用BigDecimal数据类型对货币值执行计算。
import java.math.BigDecimal;/**from NowJava.com - 时 代 Java**/ import java.text.NumberFormat; import java.util.Locale; public class Main { public static void main(String[] args) { BigDecimal currencyOne = new BigDecimal("25.65"); BigDecimal currencyTwo = new BigDecimal("187.32"); BigDecimal currencyThree = new BigDecimal("4.86"); BigDecimal result = null; String printFormat = null; // Add all three values result = currencyOne.add(currencyTwo).add(currencyThree); // Convert to double and send to formatDollars(), returning a String/*来自 n o w j a v a . c o m - 时 代 Java*/ printFormat = formatDollars(result.doubleValue()); System.out.println(printFormat); // Subtract the first currency value from the second result = currencyTwo.subtract(currencyOne); printFormat = formatDollars(result.doubleValue()); System.out.println(printFormat); } /** * Formats a double value into currency format and then returns it as a String * * @param value * @return */