18

I am facing an issue where I need to do some calculations with a number like for example 5000,00 multiplied it by (1,025^3).

So in this case 5000,00 * (1,025^3) = 5385,45

So my question is, how can I format the number 5385,45 to be like 5.385,45 using decimal format maybe?

I tried by myself and I did this piece of code that outputs 5385,45 in the app but not 5.385,45

    var interestValue = (5000,00*(Math.pow(1.025,yearValue)))
    val number = java.lang.Double.valueOf(interestValue)
    val dec = DecimalFormat("#,00")
    val credits = dec.format(number)
    vValueInterest.text = credits
José Nobre
  • 401
  • 1
  • 5
  • 14

4 Answers4

28

This is the format you need:

val dec = DecimalFormat("#,###.##")

will print:

5.384,45

if you need always exactly 2 digits after the decimal point:

val dec = DecimalFormat("#,###.00") 
forpas
  • 117,400
  • 9
  • 23
  • 54
  • 4
    0 will be printed as .00 instead of 0.00. Just use `String.format("%.2f", number)` – Choletski Dec 18 '19 at 20:01
  • @Choletski `0` will be printed as `0`. The question is not about formatting fixed decimal places but about formatting a number like `5385,45` to `5.385,45`, meaning about the thousands separator. – forpas Dec 18 '19 at 20:11
  • 4
    If you need `0` to be printed as `0.00`, you can use `DecimalFormat("#,##0.00")`. – Togashi Sep 16 '20 at 12:05
12
val num = 1.34567
val df = DecimalFormat("#.##")
df.roundingMode = RoundingMode.CEILING

println(df.format(num))

When you run the program, the output will be: 1.34

Check: https://www.programiz.com/kotlin-programming/examples/round-number-decimal

Karim
  • 492
  • 2
  • 8
2

Used:

%.numberf

fun main(args: Array<String>) {
var A: Double
A = readLine()!!.toDouble()
var bla = A*A
var calculator = 3.14159 * bla
println("A=%.4f".format(calculator))
}
scott_lotus
  • 2,977
  • 19
  • 43
  • 66
0

Try val dec = DecimalFormat("#.###,00"). For examples of DecimalFormat check this link.