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.pri
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()
You need to cast the expression to float
. I used a float literal here 100.0f
.
a.total= a.precio*a.iva/100.0f;
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)
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;
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;
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.