user1818125
user1818125

Reputation: 261

Data type for currency in Kotlin

I'm new for Kotlin. I did search and read the docs but couldn't figure out What the best data type to use in Kotlin for currency. In Java there is BigDecimal. Is there something similar in Kotlin? Thanks in advance.

Upvotes: 21

Views: 19065

Answers (3)

gidds
gidds

Reputation: 18577

If you're targeting the JVM, then you can use BigDecimal in Kotlin, too (as other answers have said) — in fact, anything that's available for Java can also be used in Kotlin!  And often in a more concise and natural way.

For example:

val a = BigDecimal("1.2")
val b = BigDecimal("3.4")

println("Sum = ${a + b}")
println("Product = ${a * b}")
val c = a / -b

That's probably the standard way to store money values right now.  If you needed extra features, you could write a class wrapping a BigDecimal along with e.g. a java.util.Currency or whatever else you needed.

(If you're targeting JS or native code, then BigDecimal isn't available, though that may change.)

The reason why it's not good practice to use floats or doubles for storing money values is that those can't store decimal values exactly (as they use floating-point binary), so are only appropriate when efficiency (of storage/calculation) is more important than precision.

If you'll never be dealing with fractions of a penny/cent/&c, then an alternative might be to store an integer number of pennies instead.  That can be more efficient, but doesn't apply very often.

(You'll note the example above creates BigDecimals from Strings.  This is usually a good idea; if you create them from floats or doubles, then the value will already have been truncated before BigDecimal gets to see it.)

Upvotes: 3

Yohan Malshika
Yohan Malshika

Reputation: 733

You can use BigDecimal in kotlin too.

var num1 : BigDecimal? = BigDecimal.ZERO

var num2  = BigDecimal("67.9") 

Also you can use Double data type and then you can use toBigDecimal() for convert it to BigDecimal.

For the more details :- https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/to-big-decimal.html

Upvotes: 17

Nirav Bhavsar
Nirav Bhavsar

Reputation: 2233

You can use BigDecimal in kotlin, please see below variable

var currency: BigDecimal? = BigDecimal.ZERO

Upvotes: 0

Related Questions