I want to save a Double variable in an Int variable but I don't know how to do it.
in Java I use this:
double doubleNumber = (int)intNumber
You can use the toDouble() method
/**
* Converts this [Int] value to [Double].
*
* The resulting `Double` value represents the same numerical value as this `Int`.
*/
public override fun toDouble(): Double
And the coude should be like this :
val intNumber: Int = 2
val doubleNumber: Double = intNumber.toDouble()
Related
I'd like to convert a Float value to a String, but without a decimal point. For example, for the following code:
fun toDecimalString(value: Float): String {
// TODO
}
fun main() {
println("Result: ${toDecimalString(1.0f)}")
println("Result: ${toDecimalString(1.999999f)}")
println("Result: ${toDecimalString(20.5f)}")
}
I'd like the expected output to be:
1
1
20
As #Tenfour04 said, the answer is to first convert to an integer, by using .toInt(), which only leaves the digits left of the decimal point, and then convert to string using .toString().
.toInt().toString()
By converting to an Int before turning the input to a string, all decimal point values are dropped, e.g.:
fun toDecimalString(value: Float): String = "${value.toInt()}"
I have two integers like val a = 5 and val b = 7. I just got curious about what is the fastest way to compute the minimum of these integers.
val min = minOf(a,b)
val min = Math.min(a,b)
val min = if(a<b) a else b
Can you tell me which one is faster and why that is faster?
They are all equally fast.
If you look at the definition of the minOf() function, you see
/**
* Returns the smaller of two values.
*/
#SinceKotlin("1.1")
#kotlin.internal.InlineOnly
public actual inline fun minOf(a: Int, b: Int): Int {
return Math.min(a, b)
}
that is, in fact, your second option.
Then, the body of Math.min() is
/**
* Returns the smaller of two {#code int} values. That is,
* the result the argument closer to the value of
* {#link Integer#MIN_VALUE}. If the arguments have the same
* value, the result is that same value.
*
* #param a an argument.
* #param b another argument.
* #return the smaller of {#code a} and {#code b}.
*/
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
that is, in fact, your third option.
KOTLIN 1.8.0
The latest one is below and working fine.
Latest : a.coerceAtMost(b)
Deprecated but still can use : Math.min(a, b)
Legacy : if(a>b) b else a
have a good day !
How to convert a string value which contains float representation to integer in kotlin?
I tried to convert string to float with .toFloat() and then converted it to an integer using toInt() and it works flawlessly.
But how to convert such string to integer directly?
val strDemo = "42.22"
val intDemo = strDemo.toInt()
snippet above throws NumberFormatException because it is not correct number representaion of Integer.
But, when I try
val strDemo = "42.22"
val intDemo = strDemo.toFloat().toInt()
it converts the data with no exception because string gets converted to float first. And there is a correct number representation for a Float value.
Now how to bypass the toFloat() method and convert strDemo to Integer directly?
There's no magic function that will convert a decimal/float string numbers to integer directly. It has to be done this way. Even if you found one, I'm sure that the process toFloat().toInt() still happen on that function.
So the solution that you can do is to create an extension of String like this:
StringExt.kt
fun String.floatToInt(): Int {
return this.toFloat().toInt()
}
You can use it like this:
val strDemo = "42.22"
val intDemo = strDemo.floatToInt()
I knew this can be achieved with for loop but I am looking for better solution.
createDummyString(1,'A') = 'A'
createDummyString(2.'A') = 'AA'
This will be used in hangman. Thank you.
You can do it like in the example below. To learn more about Strings read this: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html
fun createDummyString(repeat : Int, alpha : Char) = alpha.toString().repeat(repeat)
Addendum:
If you want to make it more kotlinesque, you can also define repeat as extension function on Char
fun Char.repeat(count: Int): String = this.toString().repeat(count)
and call it like this:
'A'.repeat(1)
CharSequence has an extension method for this.
fun CharSequence.repeat(n: Int): String // for any whole number
Example
println("A".repeat(4)) // AAAA
println("A".repeat(0)) // nothing
println("A".repeat(-1)) // Exception
Reference : https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/repeat.html
I created a utility function using infix operator for this :
infix fun Int.times(s : CharSequence): CharSequence{
return s.repeat(this)
}
//Use like val twoAs = 2 times "A"
println(a) // AA
I currently start to learn Kotlin and I was making this code
val a = "1"
val b = a[0]
val c = b.toInt()
println(c)
When I run the code, the result is 49. What really happened? Because I think the result will be 1.
a is a String, which is a CharSequence. That is why you can access a[0] in the first place. a.get(0) or a[0] then returns a Char. Char on the other hand returns its character value when calling toInt(), check also the documentation of toInt().
So your code commented:
val a = "1" // a is a String
val b = a[0] // b is a Char
val c = b.toInt() // c is (an Int representing) the character value of b
If you just want to return the number you rather need to parse it or use any of the answers you like the most of: How do I convert a Char to Int?
(one simple way being b.toString().toInt()).
a is String,
when you get a[index] return type is char,
in kotlin char.toInt method return ASCII code of the character and it's 49
if you want to get the integer value of "1" just use toString method
val a = "1"
val b = a[0].toString()
val c = b.toInt()
println(c)
prints:1
In your example a is a String, but String. String is under the hood an Array of Char. And by accessing your String using a[0] operator, you get first element of this Char Array. So you get Char '1', not String "1". And now, when you run '1'.toInt() function on Char - it will return ASCII code of that Char. When you run "1".toInt() on String - it will convert this String into Int "1". When you need to get Int value of first letter in your String, you need to convert it first into String:
val a = "123"
val b = a[0].toString() // returns first Char of String "123" and converts to String
val c = b.toInt() // returns Int: 1
or in one line:
"123"[0].toString().toInt()