我已经这样定义了formatter
:
>>> import java.text.NumberFormat
>>> val formatter = NumberFormat.getInstance()
看来formatter.parse("1,000")
的结果是Long
:
>>> formatter.parse("1,000")::class
class kotlin.Long
但是,如果我尝试将其传递给BigDecimal
的构造函数,则会收到一条错误消息,指出它与任何构造函数都不匹配:
>>> BigDecimal(formatter.parse("1,000"))
error: none of the following functions can be called with the arguments supplied:
public constructor BigDecimal(p0: BigInteger!) defined in java.math.BigDecimal
public constructor BigDecimal(p0: CharArray!) defined in java.math.BigDecimal
public constructor BigDecimal(p0: Double) defined in java.math.BigDecimal
public constructor BigDecimal(p0: Int) defined in java.math.BigDecimal
public constructor BigDecimal(p0: Long) defined in java.math.BigDecimal
public constructor BigDecimal(p0: String!) defined in java.math.BigDecimal
BigDecimal(formatter.parse("1,000"))
^
尽管如此
>>> formatter.parse("1,000") == 1000L
true
知道我在做什么错吗?
答案 0 :(得分:2)
在科特林
formatter.parse("1,000") //this result in not Long.Its is Number
所以您必须转换为Long
fun main()
{
val formatter = NumberFormat.getInstance()
val result:Number=formatter.parse("1,000")
val decimal=BigDecimal(result.toLong())
println(decimal) //out put is 1000
}
答案 1 :(得分:1)
您需要将值转换为Long,然后再将其传递给BigDecimal
构造函数,因为它是Number
。您可以使用.toLong()
或为Number
创建扩展函数,该函数返回BigDecimal:
fun Number.bigDecimialValue(): BigDecimal = BigDecimal(this.toLong())