TomE
TomE

Reputation: 1

how to display string with paramters in Kotlin/android setText without string concantenation?

I used the following to output 6 Doubles in a string, using string concatenation. Worked for me but I guess is poor practice (string concatenation in setText).

allUpM_TextView.setText(
"Mass [kg]: %.0f".format(AllUpM) + " Mass/V [kg/m2]: %.3f".format(MperV) +
"\nMax Alt [m]: %.1f".format(Alt) +
"\nTemp [deg C]: %.1f".format(Temp_a) +
"\nPres [mBar]: %.1f".format(Pres_a) +
"\nLift [kg]: %.1f".format(Lift) )

So I wanted to do it with a resource string:

 <string name="outputTxt">Mass [kg]: %1$s Mass/V [kg/m2]: %2$s
                        \nMax Alt [m]: %3$s
                        \nTemp [deg C]: %4$s  nPres [mBar]: %5$s
                        \nLift [kg]: %6$s</string>

and

val string = getString(R.string.outputTxt,
        AllUpM.toString(),
        MperV.toString(),
        Alt.toString(),
        Temp_a.toString(),
        Pres_a.toString(),
        Lift.toString()
        )

allUpM_TextView.setText(string)

The Doubles are output to full precision.

How do I implement some formatting of the Double like "%.1f" or "%.3f"?

Any help for someone on their first Android App after having last programmed Fortan 30 years ago.

Upvotes: 0

Views: 402

Answers (1)

Merthan Erdem
Merthan Erdem

Reputation: 6068

fun Double.toFormattedString(n : Int) : String {
    return "%.${n}f".format(this).toString() // not tested, maybe toString isn't required
}

This will help you get n decimal places (called extension function in case you haven't seen that syntax before)

Afterwards use it on each double instead of calling toString:

val string = getString(R.string.outputTxt,
        AllUpM.toFormattedString(2),
        MperV.toFormattedString(2),
        Alt.toFormattedString(2),
        Temp_a.toFormattedString(2),
        Pres_a.toFormattedString(2),
        Lift.toFormattedString(2)
        )

allUpM_TextView.setText(string)

Upvotes: 1

Related Questions