The default of Double
in android kotlin is 1121.57
. How to convert it to 1.121,5767
to make 4 number after comma
? even though behind the comma is 0
like this: 1.121,0000
Asked
Active
Viewed 1,717 times
1

R Rifa Fauzi Komara
- 1,915
- 6
- 27
- 54
-
I think what you are looking for is String.format. Nothing kotlin specific needed there, look up java docs. – kolboc May 26 '20 at 10:17
-
can you give me a link to the docs? Because I confused what query of googling for that – R Rifa Fauzi Komara May 26 '20 at 10:18
-
Or you can give me a sample code to convert it. – R Rifa Fauzi Komara May 26 '20 at 10:18
-
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html the specific thing you might be interested in is '#' - The result should use a conversion-dependent alternate form. DecimalFormat might come in handy too: https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java?rq=1 – kolboc May 26 '20 at 10:27
3 Answers
3
You could write an extension function for Double
and use a German format for the output, like this:
fun main() {
val myDouble: Double = 1121.57
val anotherDouble: Double = 100000.99
println(myDouble.format(4))
println(anotherDouble.format(4))
}
fun Double.format(digits:Int) = String.Companion.format(
java.util.Locale.GERMAN,
"%#,.${digits}f",
this
)
It returns the following String
1.121,5700
100.000,9900

deHaar
- 17,687
- 10
- 38
- 51
0
please pass your value to the following function and let me know if it works for you.
fun formattedNumber(number: Double): String{
val formattedNumber = String.format("%.7f", number)
val split = formattedNumber.split(".");
val str = StringBuilder(split[1])
str.insert(3, ',')
return "${split[0]}.${str}"
}

mujeeb.omr
- 499
- 2
- 12
0
Take a look at the BigDecimal class. You can easily set the scale to 4 digits and it can be created with a Double.

Wirling
- 4,810
- 3
- 48
- 78