1
fun Add() { var num1 by remember { mutableStateOf("") } var num2 by remember { mutableStateOf("") } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Arrangement.CenterHorizontally, ) { TextField( value = num1, onValueChange = { num1 = it }) TextField (value = num2, onValueChange = { num2 = it }) } remember { mutableStateOf("") } val sum = num1 + num2 Column( modifier = Modifier.fillMaxsize(), verticalAlignment = Alignment.End ) { Button(onClick = { Toast.maketext( context, "result:$sum", Toast.LENGTH_SHORT ).show() }) { Text("output") } } } 

I'm getting output as concatenated values eg: 5 + 5 = 55 but I need out put as 5 + 5 = 10 sum of numbers.

2
  • No, I tried that but it dint worked for me Commented Oct 16, 2021 at 6:00
  • That's exactly the same as the answer you accepted (use .toInt()) Commented Oct 16, 2021 at 6:00

2 Answers 2

1

This is no different than any other string to number conversion, instead of

val sum = num1 + num2 

do

val sum = (num1.toInt() + num2.toInt()).toString() 
Sign up to request clarification or add additional context in comments.

2 Comments

I implemented this method but app crashed . In logcat I get error as "E/AndroidRuntime: FATAL EXCEPTION: main"
You have to check the input before converting to an integer to ensure it is formatted correctly, my answer is just the starting point, you always need to validate input.
0

Use use num1.toInt() and num2.toInt() to add the numbers up.

Comments