androidkotlinandroid-jetpack-composeandroid-slider

Round RangeSlider position values to 2 decimal places


I'm trying to create a price range slider in Compose, I've found something that almost suits my needs:

@Composable
@OptIn(ExperimentalMaterialApi::class)
fun RangeSliderSample() {
    var sliderPosition by remember { mutableStateOf(0f..100f) }
    Text(text = sliderPosition.toString(), style = MaterialTheme.typography.labelLarge)
    RangeSlider(
        values = sliderPosition,
        onValueChange = { sliderPosition = it },
        valueRange = 0f..100f,
        onValueChangeFinished = {
            // launch some business logic update with the state you hold
            // viewModel.updateSelectedSliderValue(sliderPosition)
        },
    )
}

however there is no (clear) way to round up the position/values to 2 decimal places (eg. 10.24 etc.) and I really need that

any tips / hints / links will be appreciated,

thanks in advance :)


Solution

  • You can round up the value:

    var sliderPosition by remember { mutableStateOf(0f..100f) }
    Text(
         text =  String.format("%.2f", sliderPosition.start) + " - " +
                 String.format("%.2f", sliderPosition.endInclusive),
         style = MaterialTheme.typography.labelLarge
    )
    

    enter image description here