Question

I'm trying to round to a different number of decimal places each time the user says so. I've been trying

BigDecimal dec = new BigDecimal(input).setScale(places, BigDecimal.ROUND_HALF_EVEN);

(and ROUND_HALF_UP, and then doingdec.doubleValue()) but it doesn't add terminal zeroes.

For example, 0.4595 becomes 0.46, not 0.460. Any help is greatly appreciated.

Était-ce utile?

La solution

Why would you call doubleValue()? Just avoid doing that. There are two problems with it:

  • A double has no notion of trailing zeroes, unlike BigDecimal
  • Converting between double and BigDecimal (in either direction) is almost always a bad idea. They're generally used for different kinds of values - e.g. physical dimensions like height and weight are best for double; artificial values such as currency are best for BigDecimal

Without the call to doubleValue() you're fine:

import java.math.*;

public class Test {
    public static void main(String[] args) {
        String input = "0.4595";
        int places = 3;
        BigDecimal dec = new BigDecimal(input)
            .setScale(places, BigDecimal.ROUND_HALF_EVEN);
        System.out.println(dec); // Prints 0.460
    }
}

Autres conseils

Change it to:

BigDecimal dec = new BigDecimal(input).setScale(3, BigDecimal.ROUND_HALF_EVEN);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top