0

I have the following formula and code:

I tried with Math.Floor, and others but I am not getting the result expected

double netPay = grossPay - totalDeduction;

System.out.printf("Net Pay: $%.2f", (netPay));

The idea is to get the number as follows:

46.225

Rounded as 46.22

and not as 46.23

Hello World
  • 207
  • 1
  • 12

3 Answers3

3

As stated by commenters: For financial purposes, use BigDecimal.

Aside from that:

double netPayCents = Math.floor(netPay * 100);
netPay = netPayCents / 100d;

Why use BigDecimal?

Floating point values(including double values) can be very precise, but they have issues when trying to be absolutely precise. They are always subject to rounding, after most mathematical operations.

See this thread for more detail: Double vs. BigDecimal?

Anubhav Singh
  • 8,321
  • 4
  • 25
  • 43
TreffnonX
  • 2,924
  • 15
  • 23
  • The `100d` in the denominator should be optional, i.e. just `/ 100` should work. But other than that, +1 to what I was about to write. – Tim Biegeleisen May 20 '19 at 05:49
  • the 'd' is indeed optional, but I prefer to avoid implicit convertions, because then I am more sure that a calculation is not accidentally done in integer or long. It's just personal preference. :) – TreffnonX May 20 '19 at 05:50
1

You can also use the below code:

import java.text.DecimalFormat;
import java.math.RoundingMode;
public class Main
{
    public static void main(String[] args) {
        double netPay = 46.225;
        DecimalFormat f = new DecimalFormat("##.00");
        f.setRoundingMode(RoundingMode.DOWN);
        System.out.println(f.format(netPay));
    }
}

Output:

46.22
Anubhav Singh
  • 8,321
  • 4
  • 25
  • 43
1

Here is the method I use:

For Example netPay value is 46.225

By using Below code you will get the output like 46.22

double netPay =46.225;           // just assigning your decimal to a variable
netPay =netPay *100;              // this sets netPay to 4622.5
netPay =Math.floor(netPay);      // this sets netPay to 4622.0
netPay =netPay/100;              // this sets netPay to 46.22

Vnstead of above code you can just use below single line it will also work the same

netPay =Math.floor(netPay*100) / 100;

Happy Coding !!!!!!!!!!!!!!