小数点四舍五入到 2 位

Rounding off a decimal to 2 places

代码

package Java.School.IX;
import java.util.*;

public class Invest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter principle - Rs ");
        double p = sc.nextDouble();
        //Interest for 1st yr - 
        double i1 = (p*3*5)/100;
        double a = Math.round(i1,2);
        System.out.println("Interest for 1st year is Rs " + a);
        //Interest for 2nd yr - 
        double p1 = p + i1;
        double i2 = (p1*3*5)/100; 
        System.out.println("Interest for 2nd year is Rs "+ i2); 
        sc.close();
    }
}

问题

我尝试使用 Math.round(double, noOfPlaces),但这段代码似乎不起作用。我需要一些指导。

请帮我把小数点四舍五入到小数点后两位。如何解决这个问题?

尝试使用 NumberFormat class。它可以将数字格式化为小数点后的确切位数。

不要四舍五入实际值。让 System.out.printf() 为您代劳。

double [] data = {1.4452, 123.223,23.229};
for (double v : data) {
   System.out.printf("%.2f%n",v);
}

打印

1.45
123.22
23.23

有多种方法可以做到这一点。

Math.round()

double i = 2.3333;
System.out.println(Math.round(i*100) / 100);

NumberFormat.format()

NumberFormat formatter = new DecimalFormat("#0.00");     
System.out.println(formatter.format(2.3333));

System.out.printf()

System.out.printf("%.2f", 3.2222);

大概还有10种方法,这就是我现在能想到的。

支持

  • 首选 BigDecimal 货币金额
// I = PRT
// Returns: interest for n-th year for principal amount (also printed on stdout)
BigDecimal interestFor(BigDecimal principalAmount, int year) {
    BigDecimal interest = principalAmount.multiply(3*5).divide(100); // FIX:  check formula here to be correct on years!

    // Locale.US for $, but if we want Indian Rupee as: Rs
    Locale locale = new Locale("en", "IN");
    String interestFormatted = NumberFormat.getCurrencyInstance(locale).format(interest);
    
    System.out.printf("Interest for year %d is %s\n", year, interestFormatted);
    
    return interest;
}

对于占位符文字 %s(字符串格式)、%d(十进制格式),请参阅 Java 的 Formatter syntax

另请参阅:

  • How to print formatted BigDecimal values?