WillSmith
WillSmith

Reputation: 104

Is there any elegant ways to convert Int to BigDecimal in Kotlin?

I'm working on my toy project with Kotlin.

While writing code, I feel that those codes are somewhat duplicated and not clean.

val a: Int = 1
val a_D: BigDecimal = a.toBigDecimal()
val b_D: BigDecimal = a.toBigDecimal()

So, is there any way to avoid those duplication(something like toBigDecimal()) using elegant way?

Upvotes: 3

Views: 7365

Answers (1)

matt freake
matt freake

Reputation: 5090

If you are bothered about having to create the BigDecimal over two lines, BigDecimal has constructors that take Int that you can call directly:

 val bigDecimalInt = BigDecimal(1)

This is fine for integer values, BUT for floating-point values like Double the constructor and toBigDecimal actually behave differently. The constructor creates a BigDecimal value of the Double value passed in, which will be "incorrect" if that value is not exactly representable in floating-point arithmetic. toBigDecimal converts the value to a String and then uses that which gives the "correct" value

val doubleNum:Double = 0.1
println(doubleNum.toBigDecimal()) // prints 0.1

val bigDecimal:BigDecimal = BigDecimal(0.1)
println(bigDecimal)               // prints 0.1000000000000000055511151231257827021181583404541015625

If none of that makes sense, you probably need to read about Floating Point Arithmetic, this is a common problem affecting all/most programming languages

So toBigDecimal is a safer option

Upvotes: 5

Related Questions