简体   繁体   中英

Rounding a double in java

I have read some other posts and they seem to work for other people, but when i try them out they don't work. I just started learning to program Java, and i cannot seem to understand how to round the decimal.

I tried

answer = input * input;
answer = answer*1000;   // Rounds the number to to three decimals points
answer = Math.round(answer);
answer = answer/1000;

i also tried (as stated in the comments) but it only displays the same number

double input = 1.0345;
Double.valueOf(new DecimalFormat("#.##").format(input));  // 2 decimal-places
System.out.println("1.0345 rounded is " + input);

but it doesn't seem to work.

If you handle precise values (especially amounts of money, interest rates, ...) you have to avoid floating point values / arithmetic. Floating point variables can take a very vide range of values but they are not precise. Especially when calculating long terms or very different quantities, you get into trouble. Rounding errors can accumulate. This is caused by the way the wide value range of decimal numbers is stored in a fixed-length 32-/64-bit binary value. For example, the innocent friendly value 0.1 is quite difficult as a binary floating point value. For details refer to the IEEE 754 specification.

Therefore, you have to use data types for exact calculation in these cases. Java offers the BigDecimal class. Another approch to avoid floating point precision errors is using only integers for calculations and then formatting the output to make it have a certain number of decimal places.

But as Java offers a nice ready-to-use class for fixed point math ( BigDecimal ), you could give it a try. Have a look at this small example code snippet. You can choose from several different rounding modes and determine how many decimal places you'd like to have.

import java.math.BigDecimal;
import java.math.RoundingMode;

public class RoundTest {

    public static void main(String[] args) {

        String userInput = "42.133742";
        BigDecimal startValue = new BigDecimal(userInput);

        BigDecimal multFactor = new BigDecimal("1.23");   // => increase by 23 %

        BigDecimal result = startValue.multiply(multFactor);

        System.out.println("Original result without rounding: " + result);
        System.out.println("Scale: " + result.scale());

        // Compare different rounding modes:

        final int DECIMAL_PLACES = 2;
        BigDecimal roundDown   = result.setScale(DECIMAL_PLACES, RoundingMode.DOWN);
        BigDecimal roundHalfUp = result.setScale(DECIMAL_PLACES, RoundingMode.HALF_UP);
        BigDecimal roundUp     = result.setScale(DECIMAL_PLACES, RoundingMode.UP);

        System.out.println("Round down (" + DECIMAL_PLACES + " decimal places): " + roundDown);
        System.out.println("Round half-up (" + DECIMAL_PLACES + " dec. places): " + roundHalfUp);
        System.out.println("Round up (" + DECIMAL_PLACES + " decimal places):   " + roundUp);

    }
}

Try this way:

answer = input * input; BigDecimal bg = new BigDecimal(answer); double rs = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

or DecimalFormat df = new DecimalFormat("#.00"); double rs = df.format(answer); DecimalFormat df = new DecimalFormat("#.00"); double rs = df.format(answer);

Using BigDecimal will always keep the pricise value for double values.

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