【问题标题】:find wheher string value is integer or decimal kotlin查找字符串值是整数还是小数 kotlin
【发布时间】:2021-10-21 23:07:30
【问题描述】:

我有从服务器响应获得的动态字符串值(例如: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()
        }

【问题讨论】:

    标签: string kotlin math integer decimal-point


    【解决方案1】:

    您似乎想显示小数点后 2 位的价格,可以这样做,无需检查点

    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()
    

    【讨论】:

      【解决方案2】:

      如果我正确理解了您的问题,请尝试:

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 谢谢。它对我有用
        • @SasidharanIOS 请在您有解决方案时将问题标记为已解决:)
        猜你喜欢
        • 1970-01-01
        • 2018-03-20
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        • 2011-09-01
        • 1970-01-01
        相关资源
        最近更新 更多