简体   繁体   中英

Round according to nearest decimal value - java

I have used this one

Math.round(input * 100.0) / 100.0;

but it didn't work with my requirement. I want to round into two decimal points according to nearest decimal value.

firstly I want to check fourth decimal value if it is 5 or above I want to add 1 into 3rd decimal value then want to check 3rd one if it is 5 or above I want to add 1 into 2nd one

ex: if I have 22.3246

refer above example number. 4th decimal no is 6. we can add 1 into 3rd decimal value.

result: 22.325

now 3rd decimal no is 5. we can add 1 into 2nd decimal value

result: 22.33

I want to get result 22.33

If you want to respect the 4th decimal digit, you can do it in this way:

double val = Math.round(22.3246 * 1000.0) / 1000.0;
double result = Math.round(val * 100.0) / 100.0;
System.out.println(result); // print: 22.33

You can use BigDecimal class to accomplish this task, in combination with a scale and RoundingMode.HALF_UP .

Sample code:

System.out.println(new BigDecimal("22.3246").divide(BigDecimal.ONE,3,RoundingMode.HALF_UP)
                    .divide(BigDecimal.ONE,2,RoundingMode.HALF_UP));

Output:

22.33

According to your requirement, the greatest number to be rounded down to 22.32 is 22.3244444444... . From 22.32444...4445 on, iteratively rounding digit per digit will lead to 22.33 .

So, you can add a bias of 0.005 - 0.0044444444 (standard rounding threshold minus your threshold), being 5/9000 and then round to the next 1/100 the standard way:

    double BIAS = 5.0 / 9000.0;
    double result = Math.round((input + BIAS) * 100.0) / 100.0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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