17

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.

user1818125
  • 221
  • 1
  • 2
  • 8
  • https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/java.math.-big-decimal/index.html – Blackbelt Aug 22 '18 at 11:23
  • My question is always why use decimals when you can just use Long, and then format according to what you need (e. g. convert Long to string and insert dot at correct position) – xdevs23 Feb 28 '22 at 18:58

3 Answers3

16

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

Yohan Malshika
  • 716
  • 1
  • 11
  • 20
  • 4
    You can convert _platform types_ (coming from JVM, not Kotlin itself) to non-null or nullable Kotlin types. In your case, you can assign `BigDecimal.ZERO` directly to `BigDecimal` instead of `BigDecimal?`, since you know the value zero will not be null. Also, I'd use `val` wherever possible. – TheOperator Aug 23 '18 at 07:53
2

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.)

gidds
  • 16,558
  • 2
  • 19
  • 26
0

You can use BigDecimal in kotlin, please see below variable

var currency: BigDecimal? = BigDecimal.ZERO
Nirav Bhavsar
  • 2,133
  • 2
  • 20
  • 24