Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How do i check if a number has decimal points (modulus solution doesn't work)

Tags:

kotlin

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()
  }
like image 394
eLn86 Avatar asked Oct 16 '17 09:10

eLn86


People also ask

How do you check whether a number is decimal or not?

function number_test(n) { var result = (n - Math. floor(n)) !== 0; if (result) return 'Number has a decimal place. '; else return 'It is a whole number.

Does mod work with decimals?

modulo doesn't work with decimals because it only accepts integers. As discussed above, you can define another procedure to see if two numbers are divisible by each other. Otherwise, the computer doesn't know how to accept non-integer numbers for modulo .

How do you check if a double value has no decimal part?

You should probably use !=


Video Answer


2 Answers

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
like image 108
jrtapsell Avatar answered Sep 30 '22 20:09

jrtapsell


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

like image 40
CoolMind Avatar answered Sep 30 '22 21:09

CoolMind