timpone
timpone

Reputation: 19969

how to compare a BigDecimal number to see if it is a whole number

I am using a BigDecimal to represent a price and want to have numbers that are equal to whole number not have the fractional part and numbers with a non-zero fractional part show two digits. Such as:

value    outputs
12.0     12
12.25    12.25
12.87    12.87

I have but it's always showing as two digits:

if !price.price.nil? && price.price.frac=='0.0' # this comparison is not working correctly
  s=helpers.number_to_currency(price.price, precision: 0, format: "%n")
else
  s=helpers.number_to_currency(price.price, precision: 2, format: "%n")
end

How would I compare a BigDecimal to see if it would be a whole number?

thx

Upvotes: 0

Views: 246

Answers (2)

Si Kelly
Si Kelly

Reputation: 703

Instead of testing for the fraction, use a NumberFormat object:

public static String formatNicely(BigDecimal bd) {
    NumberFormat formatter = NumberFormat.getNumberInstance();
    formatter.setMinimumFractionDigits(0);
    formatter.setMaximumFractionDigits(2);
    return formatter.format(bd);
}

Upvotes: 0

jklina
jklina

Reputation: 3417

.frac doesn't produce a String, it produces a BigDecimal. You can try the following:

if !price.price.nil? && price.price.frac==0

That should be the comparison you're looking for.

Upvotes: 1

Related Questions