theJava
theJava

Reputation: 15034

Rounding numbers by removing/truncating zero's

I have an issue where i am getting values like this. "0.5" and 1.0

BigDecimal bd = new BigDecimal(d).setScale(1, RoundingMode.HALF_EVEN);
d = bd.doubleValue();

If i get the value as 0.5, i need to display as it is. But when i am getting 1.0, i need to display it as 1 instead of 1.0. If i alter my setScale(0), i would get 0 instead of 0.5.

DecimalFormat df = new DecimalFormat("#.0");
df.format(0.912385);

I tried with decimal format too for the sa,e

Upvotes: 0

Views: 71

Answers (4)

Jack Harkness
Jack Harkness

Reputation: 810

if(a % 1 != 0) System.out.println("Is a decimal" + yournumber)
else System.out.Println("Is not a decimal" + (int) yournumber)

Upvotes: 0

fge
fge

Reputation: 121720

Use:

myBiDecimal.stripTrailingZeros()

However, beware that this will turn 10 into 1e+1

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

You can do by DecimalFormat(String pattern);

DecimalFormat df = new DecimalFormat("#.#");
df.format(0.912385);

Upvotes: 3

Reimeus
Reimeus

Reputation: 159784

Adjust the pattern so that it suppresses non significant digits after the decimal point

DecimalFormat df = new DecimalFormat("#.#");

Upvotes: 5

Related Questions