Enigma
Enigma

Reputation: 351

How can I format a String number to have commas in Kotlin?

i have this code to calculate distance from 2 points(lat,lon)

val distance = distanceInKm(3.140853,21.422510,101.693207,39.826168)
val number3digits:Double = String.format("%-10.4f%n%n", distance).toDouble()
distancetomakkah.text = "$number3digits"

but i'm getting this output:

10891.3684

and i want the output to be like this:

10,891

i tried to change the format to: ("%-10.4f%n%n"),("%,d") and many others but i keep getting this error

f != java.lang.string

what am i doing wrong here?

Upvotes: 1

Views: 3455

Answers (2)

Steven Jeuris
Steven Jeuris

Reputation: 19130

String.format("%-10.4f%n%n", distance).toDouble()

Your format is not being applied. After formatting your returned value of distanceInKm as a String, you are calling toDouble, undoing any formatting you did.

distancetomakkah.text = "$number3digits"

number3digits is a Double, and default formatting is applied when you use string interpolation to assign .text.

Upvotes: 4

g00se
g00se

Reputation: 4296

Try

String.format("%-,10.4f%n%n", distance);

The result is of type String That wouldn't be portable of course, since the , is not used in some Locales

Upvotes: 2

Related Questions