Guys, i write a code for a program that have money...
# getting-started
d
Guys, i write a code for a program that have money on it, i am using
Match.ceil
feature for this, to predict they payment the buyer gonna use. The problem is for use
Match.ceil
i need to have the number in
float
, but then i read this https://stackoverflow.com/a/3730040 , which is telling that a bad one to use
float
for financial purpose. What i need to do? My code is something like this :
Copy code
val a: Double = valueInput1.toDouble()
    val b: Double = 5000.toDouble()
    val c = Math.ceil(a/b)*5000
    println(c)
s
Are you writing this for the JVM?
d
Android precisely @Shawn
s
Did you read the SO answer?
d
sorry, but what is SO? StackOverflow? yes i read them
i have some plan on my mind, to have things run like how my example code in here then transform it to
BigDecimal
and then save it to my Database, but i just worried if my logic is correct or not
s
if at any point you call
.toDouble()
you lose the precision you would have with
BigDecimal
d
And i think i can to make it
BigDecimal
from the start, but AFAIK
Match.ceil
only can process
Double
😐
s
It’s
Math.ceil
like Mathematics, firstly
Secondly,
BigDecimal
provides
setScale
, which you can use to perform rounding operations
d
okay i think im wrong in here, can you eli5 me Shawn?
seems like your answer and think is something that i doesn't think possible before.
s
To round a given BigDecimal to int like you would with
Math.ceil()
, you’d need something that looks kinda like this
Copy code
val intValue = bigDecimal.setScale(0, RoundingMode.CEILING).intValueExact()
But this isn’t Kotlin-related. You just need to read through the
BigDecimal
docs. https://developer.android.com/reference/java/math/BigDecimal
If you perform this rounding operation a lot, this would maybe be a good candidate for an extension
fun
.
d
hmm, seems interesting, thanks @Shawn i gonna try this