I have implemented a discrete slider like this:
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            YourProjectNameTheme(darkTheme = false) {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(all = 4.dp),
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        MyUI()
                    }
                }
            }
        }
    }
}
@Composable
private fun MyUI() {
    var sliderValue by remember {
        mutableStateOf(1f)
    }
    Slider(
        value = sliderValue,
        onValueChange = { sliderValue_ ->
            sliderValue = sliderValue_
        },
        onValueChangeFinished = {
            // this is called when the user completed selecting the value
        },
        valueRange = 1f..21f,
        steps = 6
    )
    Text(text = sliderValue.toString())
}
The output:

I'm expecting exact numbers (like 3, 6, 9, 12, 15, 18) when I tap on the tick marks. But, it is showing the nearest float value. How to fix this?
The steps attribute if greater than 0, specifies the amounts of discrete values, evenly distributed between across the whole value range.
In you case you have to use valueRange = 0f..21f
    Slider(
        //...
        valueRange = 0f..21f,
        steps = 6
    )

That's because you are starting from 1 instead of 0. Please plan the value and the steps accordingly,
@Preview
@Composable
private fun MyUI() {
    var sliderValue by remember {
        mutableStateOf(0)
    }
    Slider(value = sliderValue.toFloat(), onValueChange = { sliderValue_ ->
        sliderValue = sliderValue_.toInt()
    }, onValueChangeFinished = {
        // this is called when the user completed selecting the value
    }, valueRange = 0f..21f, steps = 6
    )
    Text(text = sliderValue.toString())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With