我想在字符串资源中的占位符内使用超过 1 种数据类型,但每当我尝试使用小数作为数值时,都会返回错误。
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,"*")
搅拌资源
<string name="distance_decimalnumber_placeholder">You have walked %1$d%2$s metres</string>
预期结果
你已经走了 5.2* 米
错误
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)
最佳答案
第一个错误d
用于整数
问题:
您已在以下位置转换为字符串:amountOut = numberFormatter.format(distanceWalked)
你现在需要用字符串替换
解决方法:不需要使用$f
您需要使用 $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>
关于android - 如何在字符串资源中使用十进制数(Double 数据类型)作为占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61466816/