0

I know the number_format function in php. I need something similar in kotlin. I found the java class NumberFormat, and it doesn't do what I need. DecimalFormat won't do it either. I also found this answered question about the number format, but it crashes when I use "0+000,00" or "#+###,##" as the format pattern.

I need to format numbers as 275+756,24.

in php I can use number_format(275756.24,2,",","+")

Is there a similar function in kotlin?

Greetings from Paraguay.

Claudio Bogado Pompa.

  • Does this answer your question? [Format number using decimal format in kotlin](https://stackoverflow.com/questions/53848189/format-number-using-decimal-format-in-kotlin). Also see [the reference](https://developer.android.com/reference/kotlin/java/text/DecimalFormat). – Jeto Feb 24 '20 at 16:50
  • No, it the app crashes when I use "0+000,00" format. It also crashes when I use "#+###,##". – Claudio Bogado Pompa Feb 24 '20 at 16:59
  • It appears [this is how you're supposed to do it](https://pl.kotl.in/VN0vjADog). I'm no Kotlin expert though. – Jeto Feb 24 '20 at 17:50
  • @Jeto Thank you. That code is a mixture of Java and Kotlin. I wrote a Java class with the code you shared, and then converted to Kotlin. – Claudio Bogado Pompa Feb 24 '20 at 19:01
  • Ah, didn't know Java classes exposed their get/set methods through Kotlin accessors. Also forgot about optional semicolons. Anyway, glad that it helped. – Jeto Feb 24 '20 at 19:38

1 Answers1

1

I hoped it was a shorter way.

val value = 275756.24
val formatter = DecimalFormat("#,###.##")
val symbols = formatter.decimalFormatSymbols
symbols.groupingSeparator = '+'
symbols.decimalSeparator = ','
formatter.decimalFormatSymbols = symbols
val result = formatter.format(value)

Thanks Jeto.