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()
}
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.
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 .
You should probably use !=
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
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With