* [PATCH yew-widget-toolkit v3] widget: form: number: round floats to some decimal precision
@ 2026-05-05 13:18 Christoph Heiss
0 siblings, 0 replies; only message in thread
From: Christoph Heiss @ 2026-05-05 13:18 UTC (permalink / raw)
To: yew-devel
The decimal precision is controllable through a property.
E.g. previously, for an input like
Number::new()
.name("some-float")
.step(0.1)
.value(0.2)
and pressing the "range-up" button on the input would result in
0.30000000000000004 - which is rather undesirable.
Rounding is done on step up, step down, on creation, on the validated
form value and on the parsed value for `on_input`, if any.
Signed-off-by: Christoph Heiss <c.heiss@proxmox.com>
---
Tested this by creating a `Number` input as in the example above,
additionally setting a callback for `on_change` and `on_input`,
verifying the (parsed, in the latter case) value is rounded as expected.
v2: https://lore.proxmox.com/yew-devel/20260327102731.490175-1-c.heiss@proxmox.com/
v1: https://lore.proxmox.com/yew-devel/20260319170432.1533393-1-c.heiss@proxmox.com/
Changes v2 -> v3:
* move rounding into own trait method
* round value and default value on creation
* round (parsed) value passed to `on_input` event
* round value passed to `on_change` event
* trigger value update when the `decimal_places` prop is changed
Changes v1 -> v2:
* added property to control precision, as suggested by Dominik
src/widget/form/number.rs | 68 +++++++++++++++++++++++++++++----------
1 file changed, 51 insertions(+), 17 deletions(-)
diff --git a/src/widget/form/number.rs b/src/widget/form/number.rs
index 942f960..b18eef5 100644
--- a/src/widget/form/number.rs
+++ b/src/widget/form/number.rs
@@ -37,12 +37,14 @@ pub trait NumberTypeInfo:
fn format(&self) -> String;
- fn step_down(&self, step: Option<Self>) -> Self;
- fn step_up(&self, step: Option<Self>) -> Self;
+ fn step_down(&self, step: Option<Self>, precision: u8) -> Self;
+ fn step_up(&self, step: Option<Self>, precision: u8) -> Self;
fn clamp_value(&self, min: Option<Self>, max: Option<Self>) -> Self;
fn is_decimal() -> bool;
+
+ fn round_to_precision(&self, precision: u8) -> Self;
}
impl NumberTypeInfo for f64 {
@@ -67,11 +69,11 @@ impl NumberTypeInfo for f64 {
fn format(&self) -> String {
crate::dom::format_float(*self)
}
- fn step_up(&self, step: Option<Self>) -> Self {
- self + step.unwrap_or(1.0)
+ fn step_up(&self, step: Option<Self>, precision: u8) -> Self {
+ (self + step.unwrap_or(1.0)).round_to_precision(precision)
}
- fn step_down(&self, step: Option<Self>) -> Self {
- self - step.unwrap_or(1.0)
+ fn step_down(&self, step: Option<Self>, precision: u8) -> Self {
+ (self - step.unwrap_or(1.0)).round_to_precision(precision)
}
fn clamp_value(&self, min: Option<Self>, max: Option<Self>) -> Self {
self.clamp(min.unwrap_or(f64::MIN), max.unwrap_or(f64::MAX))
@@ -79,6 +81,12 @@ impl NumberTypeInfo for f64 {
fn is_decimal() -> bool {
true
}
+ fn round_to_precision(&self, precision: u8) -> Self {
+ // Do a little dance here to round to the nearest step value, by multiplying,
+ // rounding to the nearest integer and dividing again
+ let m = 10f64.powf(precision as f64);
+ (self * m).round() / m
+ }
}
// Note: Error message from rust parse() are not gettext translated, so try to do all
@@ -137,7 +145,7 @@ macro_rules! signed_number_impl {
fn format(&self) -> String {
(*self).to_string()
}
- fn step_down(&self, step: Option<Self>) -> Self {
+ fn step_down(&self, step: Option<Self>, _precision: u8) -> Self {
let step = step.unwrap_or(1);
if *self >= (<$T>::MIN + step) {
self - step
@@ -145,7 +153,7 @@ macro_rules! signed_number_impl {
*self
}
}
- fn step_up(&self, step: Option<Self>) -> Self {
+ fn step_up(&self, step: Option<Self>, _precision: u8) -> Self {
let step = step.unwrap_or(1);
if *self <= (<$T>::MAX - step) {
self + step
@@ -159,6 +167,9 @@ macro_rules! signed_number_impl {
fn is_decimal() -> bool {
false
}
+ fn round_to_precision(&self, _precision: u8) -> Self {
+ *self
+ }
}
};
}
@@ -216,7 +227,7 @@ macro_rules! unsigned_number_impl {
fn format(&self) -> String {
(*self).to_string()
}
- fn step_down(&self, step: Option<Self>) -> Self {
+ fn step_down(&self, step: Option<Self>, _precision: u8) -> Self {
let step = step.unwrap_or(1);
if *self >= (<$T>::MIN + step) {
self - step
@@ -224,7 +235,7 @@ macro_rules! unsigned_number_impl {
*self
}
}
- fn step_up(&self, step: Option<Self>) -> Self {
+ fn step_up(&self, step: Option<Self>, _precision: u8) -> Self {
let step = step.unwrap_or(1);
if *self <= (<$T>::MAX - step) {
self + step
@@ -238,6 +249,9 @@ macro_rules! unsigned_number_impl {
fn is_decimal() -> bool {
false
}
+ fn round_to_precision(&self, _precision: u8) -> Self {
+ *self
+ }
}
};
}
@@ -317,6 +331,14 @@ pub struct Number<T: NumberTypeInfo> {
#[prop_or_default]
pub step: Option<T>,
+ /// Number of decimal places to round to in case of floating point numbers.
+ /// Defaults to 5 decimal places, which should cover most most cases.
+ ///
+ /// Does nothing for integers.
+ #[builder(IntoPropValue, into_prop_value)]
+ #[prop_or(5)]
+ pub decimal_places: u8,
+
/// Force value.
///
/// To implement controlled components (for use without a FormContext).
@@ -507,10 +529,13 @@ impl<T: NumberTypeInfo> ManagedField for NumberField<T> {
value = force_value.to_string().into();
}
- let value: Value = value.clone();
+ let value = match T::value_to_number(&value) {
+ Ok(v) => v.round_to_precision(props.decimal_places).into(),
+ _ => value.clone(),
+ };
let default = match props.default {
- Some(default) => T::number_to_value(&default),
+ Some(default) => T::number_to_value(&default.round_to_precision(props.decimal_places)),
None => Value::Null,
};
@@ -527,7 +552,11 @@ impl<T: NumberTypeInfo> ManagedField for NumberField<T> {
fn value_changed(&mut self, ctx: &super::ManagedFieldContext<Self>) {
let props = ctx.props();
let data = match &self.result {
- Ok(value) => Some(T::value_to_number(value).map_err(|err| err.to_string())),
+ Ok(value) => Some(
+ T::value_to_number(value)
+ .map(|v| v.round_to_precision(props.decimal_places))
+ .map_err(|err| err.to_string()),
+ ),
Err(err) => Some(Err(err.clone())),
};
if let Some(on_change) = &props.on_change {
@@ -537,7 +566,10 @@ impl<T: NumberTypeInfo> ManagedField for NumberField<T> {
fn changed(&mut self, ctx: &ManagedFieldContext<Self>, old_props: &Self::Properties) -> bool {
let props = ctx.props();
- if props.value != old_props.value || props.valid != old_props.valid {
+ if props.value != old_props.value
+ || props.valid != old_props.valid
+ || props.decimal_places != old_props.decimal_places
+ {
ctx.link().force_value(
props.value.as_ref().map(|v| v.to_string()),
props.valid.clone(),
@@ -552,7 +584,9 @@ impl<T: NumberTypeInfo> ManagedField for NumberField<T> {
Msg::Update(input) => {
ctx.link().update_value(input.clone());
if let Some(on_input) = &props.on_input {
- let value = T::value_to_number(&input.clone().into()).ok();
+ let value = T::value_to_number(&input.clone().into())
+ .map(|v| v.round_to_precision(props.decimal_places))
+ .ok();
on_input.emit((input, value));
}
true
@@ -562,7 +596,7 @@ impl<T: NumberTypeInfo> ManagedField for NumberField<T> {
let n = match (n, self.result.is_ok()) {
(None, true) => Some(T::default().clamp_value(props.min, props.max)),
(Some(n), _) => {
- let next = T::step_up(&n, props.step);
+ let next = T::step_up(&n, props.step, props.decimal_places);
match props.max {
Some(max) if next <= max => {}
None => {}
@@ -582,7 +616,7 @@ impl<T: NumberTypeInfo> ManagedField for NumberField<T> {
let n = match (n, self.result.is_ok()) {
(None, true) => Some(T::default().clamp_value(props.min, props.max)),
(Some(n), _) => {
- let next = T::step_down(&n, props.step);
+ let next = T::step_down(&n, props.step, props.decimal_places);
match props.min {
Some(min) if next >= min => {}
None => {}
--
2.53.0
^ permalink raw reply related [flat|nested] only message in thread
only message in thread, other threads:[~2026-05-05 13:27 UTC | newest]
Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-05-05 13:18 [PATCH yew-widget-toolkit v3] widget: form: number: round floats to some decimal precision Christoph Heiss
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox