Search code examples
kotlinnumber-formatting

Converting the result of NumberFormat.parse() into a BigDecimal


I've defined a formatter like so:

>>> import java.text.NumberFormat
>>> val formatter = NumberFormat.getInstance()

It would appear that the result of formatter.parse("1,000") is a Long:

>>> formatter.parse("1,000")::class
class kotlin.Long

However, if I try to pass it to the constructor of BigDecimal, I get an error message saying that it doesn't match any of the constructors:

>>> 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"))
^

This is despite that

>>> formatter.parse("1,000") == 1000L
true

Any idea what I'm doing wrong here?


Solution

  • In kotlin

     formatter.parse("1,000") //this result in not Long.Its is Number
    

    so you have to convert as 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
    
    }