Dividing by 100 returns 0

后端 未结 6 1868
一向
一向 2021-01-17 02:13

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         


        
相关标签:
6条回答
  • 2021-01-17 02:55

    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()
    
    0 讨论(0)
  • 2021-01-17 02:58

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

    a.total= a.precio*a.iva/100.0f;
    
    0 讨论(0)
  • 2021-01-17 03:02

    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)
    
    0 讨论(0)
  • 2021-01-17 03:02

    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;
    
    0 讨论(0)
  • 2021-01-17 03:10

    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;
    
    0 讨论(0)
  • 2021-01-17 03:14

    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.

    0 讨论(0)
提交回复
热议问题