Home >Java >javaTutorial >How to use the formatting method of java BigDecimal

How to use the formatting method of java BigDecimal

WBOY
WBOYforward
2023-05-14 19:25:041843browse

1. Description

Take using BigDecimal to format currency and percentage as an example. First, create a BigDecimal object, perform BigDecimal arithmetic operations, and establish currency and percentage formatted references respectively. Finally, use the BigDecimal object as a parameter of the format() method to output its formatted currency value and percentage.

2. Example

    NumberFormat currency = NumberFormat.getCurrencyInstance(); //建立货币格式化引用
    NumberFormat percent = NumberFormat.getPercentInstance();  //建立百分比格式化引用
    percent.setMaximumFractionDigits(3); //百分比小数点最多3位
    
    BigDecimal loanAmount = new BigDecimal("15000.48"); //贷款金额
    BigDecimal interestRate = new BigDecimal("0.008"); //利率   
    BigDecimal interest = loanAmount.multiply(interestRate); //相乘
 
    System.out.println("贷款金额:\t" + currency.format(loanAmount));
    System.out.println("利率:\t" + percent.format(interestRate));
    System.out.println("利息:\t" + currency.format(interest));

What is Java

Java is an object-oriented programming language that can write desktop applications, Web applications, Distributed systems and embedded systems applications.

The above is the detailed content of How to use the formatting method of java BigDecimal. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete