Trying to get my head around the correct way to do...
# getting-started
b
Trying to get my head around the correct way to do calculations when the number I am wanting is a Float but the numbers I am using to do the calculation are integers> i.e.
val purchasedTickets: Int = 10
val totalTickets: Int = 100
percentagePurchased = (purchasedTickets/ totalTickets) * 100
This is obviously going to truncate the numbers inside the brackets so the answer will be wrong but what is the correct way to handle this?
c
Copy code
val purchasedTickets: Int = 10
    val totalTickets: Int = 100
    val percentagePurchased = (purchasedTickets.toFloat()/ totalTickets.toFloat()) * 100F
is this what you're looking for?
b
Thanks, or maybe
Copy code
percentagePurchased = (purchasedTickets.toFloat() / totaltickets) * 100
However, still testing.
c
yeah that should work
e
I would default to Double unless you have a reason to use Float
Float can only represent integers in the range [-2^24, 2^24] exactly; integers outside of that range get rounded to a multiple of a power of 2:
Copy code
val x = 50000000
x + 1 == x // false, of course
x.toFloat() + 1f == x.toFloat() // true due to running out of precision
this can happen with Double too, but you have up to 2^53
b
Yes, double safer. Whats the perfomance hit?
e
depends on hardware
on x86-32 it doesn't matter: everything goes through the 80-bit x87 coprocessor anyway
on x86-64 double tends to be faster
but double takes twice as much memory, so if you have large arrays of them, float may be better
(apparently there's ARM processors without native Double support though, so Float is way faster for them)
b
OK, so doble generally seems the way to go.
m
double for generic use, float for speed, BigDecimal for precision. Thats my general usage