I have two st.number_inputs() I am trying to use
input1 = st.number_input("x", value=5.0, step=0.5, format="%0.1f")
input2 = st.number_input("y", value=-110)
They work great, except for a few specific cases. As for input1, I’d like for it to always be rounded to the nearest half number. The step works, but when a float such as 5.4 is given, the number is not rounded and the step behaves as normal and it goes from 5.4, 5.9, etc. when I’d like the 5.4 to be rounded to 5.5 and behave like 5.5, 6.0, etc… Is there a way to always round any given number to the nearest 0.5?
As for input2, I’d like to start counting the opposite direction once the number gets above -100. ie, instead of -102, -101, -100, -99, I’d like for it to go -102, -101, -100, +101, +102, … etc. Is it possible to add conditionals like this to an st.number_input()? Furthermore, If any number between -100 and +100 is given, I’d like to round it (similar to input1) to either -100 or +100, whichever is closer.
So basically, my question boils down to two main topics: is it possible to round a number given to st.number_input() and add certain conditionals?
I've tried using .format()
but the number input is a string so that doesn't work. As for the rounding, is there printf format for rounding to the nearest 0.5 I can add to the format argument? No idea where to start with what I'm trying to achieve for input2
, though.
Since I answered this question over on the Streamlit forums, I'll also post the answer here:
You can use a callback to round on_change.
import streamlit as st
# For the first widget (display in increments of 0.5)
def forced_round():
st.session_state.half = round(st.session_state.half*2)/2
st.number_input('Half Steps',0.0,10.0, step=.5, key='half', on_change=forced_round)
# For the second widget (prevent values between -100 and 100)
def skip_100(previous):
if previous == 100 and st.session_state.zone == 99:
st.session_state.zone = -100
elif previous == -100 and st.session_state.zone == -99:
st.session_state.zone = 100
elif 0 <= st.session_state.zone < 100:
st.session_state.zone = 100
elif -100 < st.session_state.zone < 0:
st.session_state.zone = -100
if 'zone' not in st.session_state:
st.session_state.zone = 100
st.number_input('No Go Zone of 100',-1000,1000, step=1, key='zone', on_change=skip_100, args=[st.session_state.zone])
The only caution is that it can't distinguish between a manually entered change or one from clicking the increment button. As such, manually typing 99 when it currently says 100 will cause it to jump down to -100. With any other current value, entering 99 will round up to 100.