简体   繁体   English

将小数点四舍五入到 2 位

[英]Rounding off a decimal to 2 places

Code代码

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();
    }
}

Issue问题

I tried using Math.round(double, noOfPlaces) , but this code doesn't seem to be working.我尝试使用Math.round(double, noOfPlaces) ,但这段代码似乎不起作用。 I need some guidance.我需要一些指导。

Pls help me to round of the decimal to 2 decimal places.请帮助我将小数点四舍五入到小数点后 2 位。 How to fix this?如何解决这个问题?

Try using the NumberFormat class.尝试使用NumberFormat类。 It can format the number with exact number of digits past decimal point.它可以用小数点后的确切位数格式化数字。

Don't round the actual value.不要四舍五入实际值。 Let System.out.printf() do the work for you.System.out.printf()为您完成工作。

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

prints印刷

1.45
123.22
23.23

There are multiple ways to do this.有多种方法可以做到这一点。

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);

Probaly there are 10 more ways of doing it, thats just what I can think of right now.可能还有 10 种以上的方法,这就是我现在能想到的。

In favor for Basil's comment :赞成Basil 的评论

  • prefer BigDecimal for currency amounts更喜欢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;
}

For the placeholder literals %s (string formatted), %d (decimal formatted), see Java's Formatter syntax .对于占位符文字%s (字符串格式)、 %d (十进制格式),请参阅 Java 的Formatter语法

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM