wbk727
wbk727

Reputation: 8408

How to use decimal numer (Double data type) as placeholder in String resource

I want to use a more than 1 data type inside a placeholder within a String resource but whenever I try to use a demical number as a numerical value, an error is returned.

Kotlin

val currentLocale = Locale.getDefault()
val distanceWalked = 5.2
val numberFormatter: NumberFormat
val amountOut: String
numberFormatter = NumberFormat.getNumberInstance(currentLocale)
amountOut = numberFormatter.format(distanceWalked)

tv.txt = getString(R.string.distance_decimalnumber_placeholder,amountOut,"*")

Stirng resouce

<string name="distance_decimalnumber_placeholder">You have walked %1$d%2$s metres</string>

Expected result

You have walked 5.2* metres

Error

java.util.IllegalFormatConversionException: d != java.lang.Double

Wrong argument type for formatting argument '#1' in distance_decimalnumber_placeholder: conversion is 'd', received String (argument #2 in method call)

Upvotes: 1

Views: 921

Answers (2)

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

First mistake d is for ints

The problem:

You aready converted to string at: amountOut = numberFormatter.format(distanceWalked) you need to replace with string now

Solution: You don`t need to use $f you need to use $s

tv.txt = getString(R.string.distance_decimalnumber_placeholder,amountOut /* this is a string also*/ ,"*")
<string name="distance_decimalnumber_placeholder">You have walked %1$s%2$s metres</string>

Upvotes: 3

AgentP
AgentP

Reputation: 7240

I would like to mention two things :

Don't use d for double ... d is treated as int so use f instead of d. So don't use this

 <string name="distance_decimalnumber_placeholder">You have walked %1$d%2$s metres</string>

And You don't need a chartype specifier to display * use * after the f like this

 <string name="distance_decimalnumber_placeholder">You have walked %1$f* metres</string>

Notice that I have added only one place holder.

Upvotes: 1

Related Questions