如何减少Kotlin中API传入的多位数十进制数字的数字?
我从 API 获取价格值,但它是多位十进制数,例如 0.4785835398457。我想将此数字减少到 3 或 4 位数字,例如 0.3234,并且我在 TextView 中显示该值。所以首先,我必须形成这个值,其次我需要将其转换为字符串。我尝试了 DecimalFormat 方法,例如 RecyclerAdapter 的 onBindViewHolder 部分。
override fun onBindViewHolder(holder: CoinListViewHolder, position: Int) {
val df = DecimalFormat("#.###")
df.roundingMode= RoundingMode.CEILING //<-----Here
df.format(coinList[position].price_usd.also { holder.itemView.coinPrice.text = it.toString() }) // <----- And here
holder.itemView.coinTicker.text= coinList[position].asset_id
holder.itemView.setOnClickListener {
listener.onItemClick(coinList, position)
}
但它没有奏效。请帮我。 提前致谢。
I'm getting a price value from an API but it's a multi-digits decimal number like 0.4785835398457. I want to reduce this number to 3 or 4 digits number like 0.3234 and I'm showing that value in a TextView. So First, I have to form this value and second I need to convert it to String. I tried that DecimalFormat method like at onBindViewHolder part of my RecyclerAdapter.
override fun onBindViewHolder(holder: CoinListViewHolder, position: Int) {
val df = DecimalFormat("#.###")
df.roundingMode= RoundingMode.CEILING //<-----Here
df.format(coinList[position].price_usd.also { holder.itemView.coinPrice.text = it.toString() }) // <----- And here
holder.itemView.coinTicker.text= coinList[position].asset_id
holder.itemView.setOnClickListener {
listener.onItemClick(coinList, position)
}
But it did not work. Please help me.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以只使用一个字符串格式化程序,它使用您想要的小数位数:
这基本上将浮点值(
f
)转换为字符串,转换为三位有效数字(.3)。格式规范位于此处,但它是有点复杂。
就您的代码而言,这:
相当于:
我假设您想要格式化价格,然后然后将其显示在
TextView
中(现在您'只是格式化它而不对结果执行任何操作),这将是这样的:即执行格式,然后对结果执行 this
You can just use a string formatter that uses the number of decimal places you want:
That basically converts a float value (
f
) to a string, to three significant digits (.3
). The format spec is here but it's a bit complex.As far as your code goes, this:
is equivalent to this:
I'm assuming you want to format the price and then display it in the
TextView
(right now you're just formatting it and doing nothing with the result), which would be this:i.e. do the format, and then do this with the result
尝试
holder.itemview.coinprice.text = df.format(coinlist [position] .price_usd)
Try
holder.itemView.coinPrice.text = df.format(coinList[position].price_usd)