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

84
July 26, 2021, at 12:20 PM

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?

Answer 1
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.

Answer 2

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

READ ALSO
How do i select dropdown values which is outside from easyui datagrid table

How do i select dropdown values which is outside from easyui datagrid table

I'm working on the Codeigniter web application where I have used the jquery easyui Datagrid table, I have created the dropdown which is outside from the easyui Datagrid table, now how do I select dropdown value when Datagrid table is loaded?

66
How to keep page content from scrolling without disabling scrolling?

How to keep page content from scrolling without disabling scrolling?

Alright so I'm really stumped by this oneHow can I lock the page's scroll position to a specific value? I can't use overflow: hidden; on the body, because that prevents scroll events from firing entirely

46
Game Maker Studio - Creating Login System Issue Stuck

Game Maker Studio - Creating Login System Issue Stuck

I've run into a major issue with one of my projects (which is currently in early access on Google Playstore) and I'm hoping for a bit of helpSo I'm using Microsoft PlayFab for my player accounts and made an option to use device ID's as a custom identifier

53