What is the best way in kotlin to convert an Int value to a Double in a certain format - kotlin

I have the following numbers:
val first: Int = 531241180
val second: Int = 653345
What would be the best way to write a function which could get first and second as input and return the following values:
output of the fist to a Double value 53.1241180
output of the second to a Double value 6.53345

If you are allowed to specify, how many numbers you want to see before dot, you can write something like this, avoiding math operations
fun intToDouble(value: Int, integerPlaces: Int): Double {
val raw = value.toString()
val sb = StringBuilder(raw)
if(integerPlaces < sb.length()) {
sb.insert(integerPlaces, ".")
} else {
return 0.0 // return 0 if operation is illegal
}
return sb.toString().toDouble()
}

Related

How do I need to write the 3rd line - Not enough information to infer type variable T

I'm new to Kotlin and try to convert a project from Java to Kotlin
I just need one last step and I don't understand what's going on :(
I'm getting a Not enough information to infer type variable T on model.predict call
override fun link(word: String): LinkSuggestion {
val input: DoubleArray = gramToInt.toArray(word)
val output: Array<Any> = model.predict(input)
// ~~~~~~~ Not enough information to infer type variable T
val maxPredictionIndex: Int = (output[output.size - 1] as Long).toInt()
val maxPredictionProbability: Double = output[maxPredictionIndex] as Double
return LinkSuggestion(word, intToLink.fromInt(maxPredictionIndex), maxPredictionProbability)
}
where model is import org.pmml4s.model.Model
The previous Java code:
#Override
public LinkSuggestion link(String word) {
double[] input = gramToInt.toArray(word);
Object[] output = model.predict(input);
int maxPredictionIndex = ((Long) output[output.length - 1]).intValue();
double maxPredictionProbability = (Double) output[maxPredictionIndex];
return new LinkSuggestion(word, intToLink.fromInt(maxPredictionIndex), maxPredictionProbability);
}
I needed to write
val output: Array<Any> = model.predict<Any>(input)

Kotlin: Pass ranges in function as arguments

Hello is it possible to pass range in Kotlin function just like in python?
I've just started learning Kotlin but I am a little bit stuck
I wish i could pass somethind like
my_gauge = Gauge('test_name',1..200, 201..300, and etc.)
for example I have a Gauge object which rotates on the base
class Gauge(val gauge_name: String,
val red_value: Float,
val orange_value: Float,
val yellow_value: Float,
val green_value: Float,
var current_value: Float,
val min_value: Float,
val max_value: Float) {
val gauge_green = 0xFF66C2A5.toInt()
val gauge_yellow = 0xFFFDD448.toInt()
val gauge_orange = 0xFFF5A947.toInt()
val gauge_red = 0xFFD53E4F.toInt()
val min_rotation: Int = 0;
val max_rotation: Int = 300;
val ratio = max_rotation / max_value;
fun calculate_rotation(): Int {
return (current_value * ratio).toInt()
}
fun get_color(): Int {
if (current_value >= red_value) {
return gauge_red
}
if (current_value > orange_value) {
return gauge_orange
}
if (current_value > yellow_value) {
return gauge_yellow
}
return gauge_green
}
}
I've just realized that it wont work with this data instead it will be better to build my logic around ranges
So my question is How to pass ranges as a param in class/function (instead of floats)
PS: The function get_colors is not correct I will fix it once I can pass ranges with when(current_value) statement
Yes, the type of a range produced by .. is ClosedRange<T>:
fun foo(floatRange: ClosedRange<Float>) {
println(floatRange.random())
}
// Usage:
foo(1f..10f)
For integer ranges, you may prefer IntRange over ClosedRange<Int> because it allows you to use it without the performance cost of boxing by using first and last instead of start and endInclusive. There is no unboxed version for other number types.
Try this in simple way, you can use range according to data type IntRange, FloatRange, LongRange etc.
fun foo(range: IntRange){
for (a in range){
println(a)
}
}
// call this function by
foo(1..10)

Multi-type ArrayList as function argument in Kotlin

I want to send an array list containing multiple types to a function (I know it is not a good practice, it is on purpose).
I don't know what type should I use for the 'numbers' argument of the function. And then how to iterate over it. I tried List but that needs a .
Thanks.
fun sum(numbers : ArrayList) : Double
{
var sum:Double = 0.0
for(i in 0 until numbers.itemCount)
{
var temp:Double = numbers.getItem(i).toDouble()
sum = sum + temp
}
return sum
}
fun main()
{
var ar = listOf("99", 1, 3.1)
println(sum(ar))
}
You can't do this without checking specific types. String.toDouble() is not the same function as Number.toDouble() even though they look the same. Your ArrayList type has to be Any to be able to accept both Strings and Numbers. Then you have to explicitly check the type. You will have to handle the case where something is not a String or a Number by throwing an exception.
You might as well make the type List<Any> instead of ArrayList<Any> to avoid the unnecessary restriction on input.
fun sum(numbers : List<Any>) : Double
{
var sum: Double = 0.0
for(item in numbers) {
val temp = when (item) {
is String -> item.toDouble()
is Number -> item.toDouble()
else -> error("Unsupported type")
}
sum += temp
}
return sum
}
There is an existing sumBy() function for lists, so you can simplify this code:
fun sum(numbers : List<Any>) : Double = numbers.sumBy {
when (it) {
is String -> it.toDouble()
is Number -> it.toDouble()
else -> error("Unsupported type")
}
}

Kotlin String to Int or zero (default value)

How can I covert String to Int in Kotlin and if it can't be then return 0 (default value).
I think the best solution is to tell value is Int and use Elvis operator to assign value 0 if it can't be converted.
val a:String="22"
val b:Int = a.toIntOrNull()?:0//22
val c:String="a"
val d:Int = c.toIntOrNull()?:0//0
To make code more concise you can create Extension Function
fun String?.toIntOrDefault(default: Int = 0): Int {
return this?.toIntOrNull()?:default
}

How to convert String to Int in Kotlin?

I am working on a console application in Kotlin where I accept multiple arguments in main() function
fun main(args: Array<String>) {
// validation & String to Integer conversion
}
I want to check whether the String is a valid integer and convert the same or else I have to throw some exception.
How can I resolve this?
You could call toInt() on your String instances:
fun main(args: Array<String>) {
for (str in args) {
try {
val parsedInt = str.toInt()
println("The parsed int is $parsedInt")
} catch (nfe: NumberFormatException) {
// not a valid int
}
}
}
Or toIntOrNull() as an alternative:
for (str in args) {
val parsedInt = str.toIntOrNull()
if (parsedInt != null) {
println("The parsed int is $parsedInt")
} else {
// not a valid int
}
}
If you don't care about the invalid values, then you could combine toIntOrNull() with the safe call operator and a scope function, for example:
for (str in args) {
str.toIntOrNull()?.let {
println("The parsed int is $it")
}
}
Actually, there are several ways:
Given:
// aString is the string that we want to convert to number
// defaultValue is the backup value (integer) we'll have in case of conversion failed
var aString: String = "aString"
var defaultValue : Int = defaultValue
Then we have:
Operation
Successful operation
Unsuccessful Operation
aString.toInt()
Numeric value
NumberFormatException
aString.toIntOrNull()
Numeric value
null
aString.toIntOrNull() ?: defaultValue
Numeric value
defaultValue
If aString is a valid integer, then we will get is numeric value, else, based on the function used, see a result in column Unsuccessful Operation.
val i = "42".toIntOrNull()
Keep in mind that the result is nullable as the name suggests.
As suggested above, use toIntOrNull().
Parses the string as an [Int] number and returns the result
or null if the string is not a valid representation of a number.
val a = "11".toIntOrNull() // 11
val b = "-11".toIntOrNull() // -11
val c = "11.7".toIntOrNull() // null
val d = "11.0".toIntOrNull() // null
val e = "abc".toIntOrNull() // null
val f = null?.toIntOrNull() // null
I use this util function:
fun safeInt(text: String, fallback: Int): Int {
return text.toIntOrNull() ?: fallback
}
In Kotlin:
Simply do that
val abc = try {stringNumber.toInt()}catch (e:Exception){0}
In catch block you can set default value for any case string is not converted to "Int".
string_name.toString().toInt()
converts string_name to String and then the resulting String is converted to int.
i would go with something like this.
import java.util.*
fun String?.asOptionalInt() = Optional.ofNullable(this).map { it.toIntOrNull() }
fun main(args: Array<String>) {
val intArgs = args.map {
it.asOptionalInt().orElseThrow {
IllegalArgumentException("cannot parse to int $it")
}
}
println(intArgs)
}
this is quite a nice way to do this, without introducing unsafe nullable values.
add (?) before fun toInt()
val number_int = str?.toInt()
You can Direct Change by using readLine()!!.toInt()
Example:
fun main(){
print("Enter the radius = ")
var r1 = readLine()!!.toInt()
var area = (3.14*r1*r1)
println("Area is $area")
}
fun getIntValueFromString(value : String): Int {
var returnValue = ""
value.forEach {
val item = it.toString().toIntOrNull()
if(item is Int){
returnValue += item.toString()
}
}
return returnValue.toInt()
}