查找字符串值是整数还是小数 kotlin

find wheher string value is integer or decimal kotlin

我有从服务器响应中获得的动态字符串值(例如:a = 18 或 a = 18.75)。我需要在 kotlin 中查找一个值是否有小数点。我需要在 discount_price

中显示它
if(product[position].discounted_price.) {
            mrp.text = "₹" + product.get(position).price
            mrp.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
            sellingprice.text = "₹" + product.get(position).discounted_price
            tv_cartvariant.text = variant.cart_count.toString()
        } else {
            mrp.text = "₹" + product.get(position).price + ".00"
            mrp.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
            sellingprice.text = "₹" + product.get(position).discounted_price + ".00"
            tv_cartvariant.text = variant.cart_count.toString()
        }

"%.2f".format(price.toDouble()) 自动将价格格式化为小数点后两位。 示例:

  • "%.2f".format(2.toDouble()) returns 2.00
  • "%.2f".format(2.36.toDouble()) returns 2.36
  • "%.2f".format(2.9244.toDouble()) returns 2.92
  • "%.2f".format(2.1093.toDouble()) returns 2.11

如果我没有正确理解你的问题,请尝试:

if(product[position].discounted_price.toString().contains('.') {
    // price has decimal dot
} else {
    // price is probably integer
}

看来你想显示小数点后两位的价格,可以按照下面的方式进行,不需要检查点

mrp.text = "₹" + "%.2f".format(product.get(position).price.toDouble())
mrp.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
sellingprice.text = "₹" + "%.2f".format(product.get(position).discounted_price.toDouble())
tv_cartvariant.text = variant.cart_count.toString()