Alex
Alex

Reputation: 780

Dividing by 100 returns 0

I just wanted to calculate the VAT, but when i divide by 100 to obtain the total price (price*VAT/100), but it returns me 0.0. Here's my code:

        a.price=sc.nextInt();

        a.vat=sc.nextInt();

        a.total=a.precio*a.iva/100;

'total' is defines as FLOAT instead of INT

Upvotes: 1

Views: 13765

Answers (6)

Carlos Verdes
Carlos Verdes

Reputation: 3147

Be careful with "/ 100" operation in Java which can lead you to miscalculations and is an expensive operation (think that the / operation is done in the binary system and not in the decimal system).

I was in a bank project where all the amounts were with two decimals in long values (for example 123.45€ were 12345), so we had to do the same operation as you ("/ 100"). We found that some amounts lead to round calculations... missing a cent (which in banking is unacceptable).

However BigDecimal handles the same operation with a simple "movePointLeft", so I recommend you to use the next code:

total = (BigDecimal.valueOf(price * VAT)).moveLeft(2).doubleValue()

Upvotes: 8

Denys Séguret
Denys Séguret

Reputation: 382160

The problem is that what you're putting in your float variable is the result of operations on integers: it's an integer. In other words, a.precio * a.iva / 100 is first evaluated to an integer (that's where you lose precision), and then this integer is assigned to a.total as a float.

You therefore need to specify that the operation a.precio * a.iva / 100 has to be done on floats by casting the integer values.

Change

a.total=a.precio*a.iva/100;

to

a.total= ((float)a.precio)*a.iva/100;

Upvotes: 2

Brian Agnew
Brian Agnew

Reputation: 272297

Welcome to integer arithmetic. You want to do this with a float or double value, and quite likely you should be using BigDecimal to maintain precision.

Upvotes: 8

Grzegorz Żur
Grzegorz Żur

Reputation: 49181

At least on of division operands must be float or double so the result is double. Otherwise the division result is integer.

a.total=a.precio*a.iva/100.0

or if you really need float, you can skip some precision

a.total=(float)(a.precio*a.iva/100.0)

Upvotes: 2

JonasVautherin
JonasVautherin

Reputation: 8033

You have to cast your integers, otherwise your result will be computed as an integer before being assigned to a.total. Something like:

a.total = (float)(a.precio) * (float)(a.iva) / 100;

Upvotes: 4

AllTooSir
AllTooSir

Reputation: 49372

You need to cast the expression to float. I used a float literal here 100.0f.

a.total= a.precio*a.iva/100.0f;

Upvotes: 19

Related Questions