#getting-started
Title
# getting-started
b

Ben Edwards

08/17/2022, 5:56 PM
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

Ciaran Sloan

08/17/2022, 6:13 PM
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

Ben Edwards

08/17/2022, 6:16 PM
Thanks, or maybe
Copy code
``percentagePurchased = (purchasedTickets.toFloat() / totaltickets) * 100``
However, still testing.
c

Ciaran Sloan

08/17/2022, 6:20 PM
yeah that should work
e

ephemient

08/17/2022, 6:26 PM
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

Ben Edwards

08/17/2022, 6:33 PM
Yes, double safer. Whats the perfomance hit?
e

ephemient

08/17/2022, 6:40 PM
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

Ben Edwards

08/17/2022, 6:47 PM
OK, so doble generally seems the way to go.
m

Michael de Kaste

08/18/2022, 9:33 AM
double for generic use, float for speed, BigDecimal for precision. Thats my general usage