我的应用程序中有一个 EditText 允许用户插入整数或浮点数,然后用户可以将该值添加到数据库中,我在 recyclerView 中显示数据库中的值,我必须检查该值用户添加的是整数或浮点数,如果是整数,我只需要显示它而不带点,如果它是浮点数,我必须显示它是三位小数..
如何存档?
我的适配器中我应该格式化值的代码如下:
fun bind(articolo: Articolo?) {
barcode.text = articolo?.barcode
qta.text = articolo?.qta.toString() // here i should check if qta is integer and if not i have to format it with three decimal
desc.text = if(articolo?.desc.isNullOrEmpty()) "-" else articolo?.desc
}
articolo?.qta 是浮动的
答案 0 :(得分:2)
浮动扩展:
fun Float.formatForQta(): String {
val floatString = this.toString()
val decimalString: String = floatString.substring(floatString.indexOf('.') + 1, floatString.length)
return when (decimalString.toInt() == 0) {
true -> this.toInt().toString()
false -> "%.3f".format(this)
}
}
用法:
val result = yourFloat.formatForQta()
答案 1 :(得分:0)
您可以使用下面的代码来检查数字是整数还是浮点数。
fun checkIfNumberIsInteger(number: String): Boolean {
try {
number.toInt()
return true
} catch (e: NumberFormatException) {
}
try {
number.toFloat()
return false
} catch (e: NumberFormatException) {
}
return false
}
答案 2 :(得分:-1)
要检查变量是否属于某种类型,您应该使用 kotlin 中的函数 is
或 Java 中的 instanceof
。
if (obj is String) {
print(obj.length)
}
if (obj !is String) { // same as !(obj is String)
print("Not a String")
}
else {
print(obj.length)
}
就你而言:
qta.text = if(articolo is Int){do your code and return a String}
答案 3 :(得分:-1)
您可以使用 kotlin 函数 toIntOrNull() 和 toFloatOrNull()