I'm trying to convert the user's height in cm to ft and inc values, and also to convert them to cm by selecting ft and inc values. I am sharing the parts I did, please help, I couldn't get out of the work.
For example, I enter 100 cm in the cm field and when I press the ft button, it needs to convert 100 cm to ft and it converts it to 3 ft 3 inches, in the same way, when I press the cm button again without changing anything, it should convert 3 ft 3 inches to cm, but 3 ft. 3 inches translates as 99 cm, in the same way, when I press ft again without changing anything, this time it is 3 ft 2 inches because it calculates over 99 cm and continues like this. I couldn't solve this problem, where could I be doing wrong, it shouldn't be like this?
view
Button(
modifier = Modifier.padding(5.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = toggleButtonBackgroundColor1),
shape = RoundedCornerShape(25.dp),
elevation = ButtonDefaults.elevation(0.dp, 0.dp),
onClick = {
if(!btnHeightIsSelected){
btnHeightIsSelected = true
btnFtIsSelected = false
isClickIn = false
isClickFt = false
onFtToCmChange(state.ft.toInt(),state.inc.toInt())
}
}) {
Text(
text = stringResource(id = R.string.cm),
color = toggleButtonTextColor1
)
}
Button(
modifier = Modifier
.padding(5.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = toggleButtonBackgroundColor2),
shape = RoundedCornerShape(25.dp),
elevation = ButtonDefaults.elevation(0.dp, 0.dp),
onClick = {
if(!btnFtIsSelected){
btnFtIsSelected = true
btnHeightIsSelected = false
onCmToFtChange(state._height)
}
}) {
Text(
text = stringResource(id = R.string.ft_in),
color = toggleButtonTextColor2
)
}
if (btnFtIsSelected) {
CustomHeightScreenIncInputField(
ftValue = state.ft,
incValue = state.inc,
ftPlaceholder = "ft",
inPlaceholder = "in",
onClickFt = {
onPickerStateChanged(HeightPickerState.FT)
isClickIn = false
isClickFt = true
},
onClickIn = {
onPickerStateChanged(HeightPickerState.IN)
isClickFt = false
isClickIn = true
}
)
} else {
CustomInputField(
isFocused = inputFocused,
placeholder = "your height (cm)",
currentValue = state._height.toString(),
onClick = {
onPickerStateChanged(HeightPickerState.HEIGHT)
})
}
viewmodel
fun onFtToCmChange(ft: Int,inc:Int) {
//val cmHeight = (ft*12 + inc) * 2.54
val totalInches = ft * 12 + inc
val cmHeight = totalInches * 2.54
_viewState.update {
it.copy(
_height = cmHeight.toInt(),
ft = ft.toString(),
inc = inc.toString(),
height = "${cmHeight.roundToInt()}"
)
}
}
fun onCmToFtChange(_height: Int) {
val totalInches = _height / 2.54
val ft = (totalInches / 12).toInt()
val inc = (totalInches % 12).toInt()
_viewState.update {
it.copy(
ftHeight = "$ft.$inc".toDouble(),
height ="$_height",
ft = ft.toString(),
inc = inc.toString()
)
}
}