简体   繁体   中英

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?

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 .

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 Locale s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM