kotlin - 无法在 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"
}
解决方案
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)
推荐阅读
- sql - 为什么“分区依据”对这里的结果有重大影响?
- r - 使用 dplyr 嵌套或分组两个变量,然后对数据执行 Cronbach 的 alpha 函数或其他统计
- java - 页面结束时的迭代返回 false
- database - Clickhouse 没有将新数据插入物化视图
- javascript - 如何使用参考访问 html 视频元素的视频控件、事件和属性
- python-3.x - LSTM 与 CNN 中张量的形状
- amazon-web-services - 求解环境:初始冻结求解失败。灵活解决重试:AWS Sagemaker
- qt - CLion & Qt :qrc/ url 在 Clion 上不起作用
- javascript - 使用 querySelector 跳转到下一个输入
- python - 如何解决comerror:PivotTable 类的PivotFields 方法失败?