Skip to content

Commit 6adae04

Browse files
authored
Use slider precision to format feathers slider label (#21325)
# Objective The slider label doesn't format consistently. For example, for precision `2` it might jump between: `20`, `20.01`, `20.02` ... `20.1`, `20.11`… which is noisy and ugly. ## Solution Format the label using the precision. ## Testing Checked the feathers example with `2`, `0` and `-1` precision. ## Showcase https://github.com/user-attachments/assets/9f30200a-a832-43df-937a-123c8d3168cf
1 parent 20f6262 commit 6adae04

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

crates/bevy_feathers/src/controls/slider.rs

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use bevy_ui::{
2323
InteractionDisabled, InterpolationColorSpace, JustifyContent, LinearGradient, Node,
2424
PositionType, UiRect, Val,
2525
};
26-
use bevy_ui_widgets::{Slider, SliderRange, SliderValue, TrackClick};
26+
use bevy_ui_widgets::{Slider, SliderPrecision, SliderRange, SliderValue, TrackClick};
2727

2828
use crate::{
2929
constants::{fonts, size},
@@ -195,7 +195,13 @@ fn set_slider_styles(
195195

196196
fn update_slider_pos(
197197
mut q_sliders: Query<
198-
(Entity, &SliderValue, &SliderRange, &mut BackgroundGradient),
198+
(
199+
Entity,
200+
&SliderValue,
201+
&SliderRange,
202+
&SliderPrecision,
203+
&mut BackgroundGradient,
204+
),
199205
(
200206
With<SliderStyle>,
201207
Or<(
@@ -208,7 +214,7 @@ fn update_slider_pos(
208214
q_children: Query<&Children>,
209215
mut q_slider_text: Query<&mut Text, With<SliderValueText>>,
210216
) {
211-
for (slider_ent, value, range, mut gradient) in q_sliders.iter_mut() {
217+
for (slider_ent, value, range, precision, mut gradient) in q_sliders.iter_mut() {
212218
if let [Gradient::Linear(linear_gradient)] = &mut gradient.0[..] {
213219
let percent_value = range.thumb_position(value.0) * 100.0;
214220
linear_gradient.stops[1].point = Val::Percent(percent_value);
@@ -218,7 +224,18 @@ fn update_slider_pos(
218224
// Find slider text child entity and update its text with the formatted value
219225
q_children.iter_descendants(slider_ent).for_each(|child| {
220226
if let Ok(mut text) = q_slider_text.get_mut(child) {
221-
text.0 = format!("{}", value.0);
227+
let label = format!("{}", value.0);
228+
let decimals_len = label
229+
.split_once('.')
230+
.map(|(_, decimals)| decimals.len() as i32)
231+
.unwrap_or(precision.0);
232+
233+
// Don't format with precision if the value has more decimals than the precision
234+
text.0 = if precision.0 >= 0 && decimals_len <= precision.0 {
235+
format!("{:.precision$}", value.0, precision = precision.0 as usize)
236+
} else {
237+
label
238+
};
222239
}
223240
});
224241
}

0 commit comments

Comments
 (0)