9

I'm new to Kotlin and came from JS. I am currently making a calculator app and am working on the '%' operator. I need to find out if the output of the 'current input * 0.01' is a whole number or with decimal points. Usually, I would use

num % 1 !== 0

but it does not work in Kotlin and gives me the error "!= operator cannot be applied to Double or Int". It is the same for Strings or Characters. My Kotlin code is below, hope someone can help! Thanks!

val percentResult: Double() = result.toDouble() * 0.01
  if(percentResult % 1 != 0) {
   result = (NumberFormat.getInstance().format(percentResult)).toString()
  } else {
   result = percentResult.toInt().toString()
  }
eLn86
  • 93
  • 1
  • 1
  • 4
  • check https://stackoverflow.com/questions/10496616/how-to-remove-the-decimal-part-from-a-float-number-that-contains-0-in-java – Atif AbbAsi Feb 23 '21 at 18:23

4 Answers4

15

In Kotlin you can use the "rem" function:

if (number.rem(1).equals(0.0))
Geeky bean
  • 475
  • 6
  • 21
10

Equivalent code

The 0 is an int, so you need to explicitly say you want a double like this:

fun factor100(n: Number) = n.toDouble() % 100.0 == 0.0

Why this probably is not what you want

For double values this may not work correctly, due to floating point errors, so you will want to check if the difference is smaller than some small amount.

An example of how this is broken is this:

fun main(args: Array<String>) {
    var x = 0.3 - 0.2         // 0.1 (ish)
    x *= 1000                 // 100 (ish)
    println(factor100(x))     // False
}

fun factor100(n: Number) = n.toDouble() % 100.0 == 0.0
jrtapsell
  • 6,719
  • 1
  • 26
  • 49
7

See https://stackoverflow.com/a/45422616/2914140.

num % 1.0 != 0.0 // But better compare with a small constant like 1e-8.

For currency:

num.absoluteValue % 1.0 >= 0.005 (or other small constant).

CoolMind
  • 26,736
  • 15
  • 188
  • 224
-1

I don't know if im just lazy searching how to do this with core functions or there are no solutions about it. So i solved it doing this:

fun Double?.checkDecimals(decimals: Int): Boolean {
    if (this == null) return false
    val comparator = 10.0.pow(decimals)
    val doubleTimesComparator = (this * comparator)
    val integerUnit = doubleTimesComparator.toInt()
    return doubleTimesComparator == integerUnit.toDouble()
}

*android

Hamlet Leon
  • 427
  • 3
  • 9