Home > database >  Rounding off a decimal to 2 places
Rounding off a decimal to 2 places

Time:05-29

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. I need some guidance.

Pls help me to round of the decimal to 2 decimal places. How to fix this?

CodePudding user response:

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.

CodePudding user response:

Don't round the actual value. Let System.out.printf() do the work for you.

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

CodePudding user response:

Try using the NumberFormat class. It can format the number with exact number of digits past decimal point.

CodePudding user response:

In favor for Basil's comment:

  • prefer BigDecimal for currency amounts
// 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.

See also:

  • Related