Why do I feel like google search is getting worse....
# getting-started
c
Why do I feel like google search is getting worse. lol. How do I write the following formatter in kotlin? I have Int cents and I want to just convert it to a price. e.g. 100 cents == $1.00, and 99 cents $0.99 and 100000 would be $1,000.00
r
Have you tried
java.text.NumberFormat
?
c
I currently have this val dollars = price / 100 val remainingCents = price % 100 val df = DecimalFormat("#,##0.00", DecimalFormatSymbols(Locale.US)) return "$${df.format(dollars + remainingCents / 100.0)}"
seems to work. But don't know if I'm missing something else basic. or if that's just what it is? 🤷
r
Depending on the precision you need but in case a
Double
is enough you can do it like this:
Copy code
val cents = 99 / 100.0
val currencyInstance = NumberFormat.getCurrencyInstance(<http://Locale.US|Locale.US>)
println(currencyInstance.format(cents))
Apart from this your solution looks fine to me
❤️ 1
👍 1
a
Using floating point numbers for money is not a good idea. Use decimal number formats for this
4
a
Yep, to avoid rounding errors it's better to use non-float number formats. For example, a simple comparison like this:
Copy code
val left = 0.5f + 0.1f;
val right = 0.7f - 0.1f;
println("$left, $right, ${left == right}")
will print
0.6, 0.59999996, false
.
r
Using floating point values in money calculations is bad. Using them for display formatting isn't.
7
r
*as long as the numbers you're displaying aren't really big; things start to fall apart around $10^14 but at this point you probably won't miss a few cents blob wink
e
Copy code
val cents = 99.toBigDecimal().scaleByPowerOfTen(-2)
NumberFormat.getCurrencyInstance(<http://Locale.US|Locale.US>).format(cents)
also works with no potential rounding (JVM only of course)
c
I feel like there's a lot of options here. But in general, im aware that floating points and money is just asking for trouble. i figured in this scenario it wouldn't be too bad since i have cents as an Int. ephemient answer looks pretty smooth though. ill try that.
Nice. swapped in that impl and all my tests pass. no more
"#,##0.00",
needed. thanks all