How can I format string "2000000.00" into "2 000 000.00" with Kotlin?
CodePudding user response:
You can do this with DecimalFormat()
:
val dec = DecimalFormat(<pattern> [, <optional, but recommended locale>])
and then replace ,
with
:
val number = 2000000.00
val dec = DecimalFormat("###,###,###,###,###.00", DecimalFormatSymbols(Locale.ENGLISH))
val formattedNumber = dec.format(number).replace(",", " ")
println(formattedNumber)
.00
is needed to keep the digits!!!
This will print:
2 000 000.00
here as a test:
@Test
fun testDecimalFormat() {
val number = 2000000.00
val dec = DecimalFormat("###,###,###,###,###.00", DecimalFormatSymbols(Locale.ENGLISH))
val formattedNumber = dec.format(number).replace(",", " ")
assertThat(formattedNumber).isEqualTo("2 000 000.00")
}
@Test
fun testDecimalFormatWithDigitValue() {
val number = 2000000.01
val dec = DecimalFormat("###,###,###,###,###.00", DecimalFormatSymbols(Locale.ENGLISH))
val formattedNumber = dec.format(number).replace(",", " ")
assertThat(formattedNumber).isEqualTo("2 000 000.01")
}
Link: https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html