首页 > 解决方案 > 无法在 Kotlin 中将给定对象格式化为数字

问题描述

使用 ConverPrice 函数时发生错误,如下所示以获取有关价格的信息。

回收站视图适配器 onBindViewHolder 中的项目价格。

作为调试的结果,错误出现在以下代码中。

priceText = "${dec.format(priceMin)} ~ ${dec.format(priceMax)}"

请检查我的代码并回答。

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

            when (holder) {
                is DataViewHolder -> {
                    val item = dataList[position]

                    item.price.let {
                        holder.price.text = ConvertPrice(item, holder.price)
                    }

                }
            }
        }

fun ConvertPrice(productDetail: ProductDetail?, tv: TextView? = null, setPrice: Boolean = false): String {
    val disableColor = Color.parseColor("#aaaaaa")
    val enableColor = Color.parseColor("#3692ff")

    tv?.setTextColor(disableColor)

    if (ProductDetail != null) {
        val priceMin = productDetail.priceMin
        val priceMax = productDetail.priceMax
        var priceText = ""

        val dec = DecimalFormat("##,###")

        productDetail.enabledRetail?.let {
            if (productDetail.enabledRetail == true) {
                if (setPrice) {
                    priceText = if (priceMin == null || priceMax == null) {
                        "No pricing information"
                    } else {
                        "${dec.format(priceMin)} ~ ${dec.format(priceMax)}"
                    }
                    tv?.setTextColor(disableColor)
                }
                else {
                    priceText = dec.format(wineDetail.price).toString()
                    tv?.setTextColor(enableColor)
                }
                return priceText
            } else if (productDetail.cntRating!! > 0) {
                if ((priceMin == null && priceMax == null) || (priceMin == 0 && priceMax == 0)) {
                    priceText = "No pricing information"
                } else {
                    priceText =
                        "${dec.format(priceMin)} ~ ${dec.format(priceMax)}"
                    tv?.setTextColor(disableColor)
                }
                return priceText
            }
        }
    }
    return "No pricing information"
}


标签: kotlin

解决方案


DecimalFormat.format()仅适用于 long 或 double。您应该将“priceMin”和“priceMax”转换为 Long。

val priceMin = productDetail.priceMin.toLong()
val priceMax = productDetail.priceMax.toLong()

我建议使用NumberFormat,而不是DecimalFormat因为它是区域敏感的

val decFormat = NumberFormat.getInstance() // or getCurrencyInstance()
decFormat.maximumFractionDigits = 3
decFormat.format(priceMin)
decFormat.format(priceMax)

推荐阅读