all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Christoph Heiss <c.heiss@proxmox.com>
To: yew-devel@lists.proxmox.com
Subject: [PATCH yew-widget-toolkit v3] widget: form: number: round floats to some decimal precision
Date: Tue,  5 May 2026 15:18:36 +0200	[thread overview]
Message-ID: <20260505132650.1158715-1-c.heiss@proxmox.com> (raw)

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





             reply	other threads:[~2026-05-05 13:27 UTC|newest]

Thread overview: 2+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-05-05 13:18 Christoph Heiss [this message]
2026-05-06 21:19 ` [PATCH yew-widget-toolkit v3] widget: form: number: round floats to some decimal precision Thomas Lamprecht

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260505132650.1158715-1-c.heiss@proxmox.com \
    --to=c.heiss@proxmox.com \
    --cc=yew-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal