From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from firstgate.proxmox.com (firstgate.proxmox.com [IPv6:2a01:7e0:0:424::9]) by lore.proxmox.com (Postfix) with ESMTPS id 690871FF141 for ; Tue, 05 May 2026 15:27:04 +0200 (CEST) Received: from firstgate.proxmox.com (localhost [127.0.0.1]) by firstgate.proxmox.com (Proxmox) with ESMTP id 18FE039F4; Tue, 5 May 2026 15:27:04 +0200 (CEST) From: Christoph Heiss 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 Message-ID: <20260505132650.1158715-1-c.heiss@proxmox.com> X-Mailer: git-send-email 2.53.0 MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1777987510869 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.076 Adjusted score from AWL reputation of From: address BAYES_00 -1.9 Bayes spam probability is 0 to 1% DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record URIBL_BLOCKED 0.001 ADMINISTRATOR NOTICE: The query to URIBL was blocked. See http://wiki.apache.org/spamassassin/DnsBlocklists#dnsbl-block for more information. [proxmox.com,number.rs] Message-ID-Hash: SAG2MMWTSCPAZVQDZ5NBV42HYFSKKN2C X-Message-ID-Hash: SAG2MMWTSCPAZVQDZ5NBV42HYFSKKN2C X-MailFrom: c.heiss@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Yew framework devel list at Proxmox List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: 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 --- 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; - fn step_up(&self, step: Option) -> Self; + fn step_down(&self, step: Option, precision: u8) -> Self; + fn step_up(&self, step: Option, precision: u8) -> Self; fn clamp_value(&self, min: Option, max: Option) -> 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 + step.unwrap_or(1.0) + fn step_up(&self, step: Option, precision: u8) -> Self { + (self + step.unwrap_or(1.0)).round_to_precision(precision) } - fn step_down(&self, step: Option) -> Self { - self - step.unwrap_or(1.0) + fn step_down(&self, step: Option, precision: u8) -> Self { + (self - step.unwrap_or(1.0)).round_to_precision(precision) } fn clamp_value(&self, min: Option, max: Option) -> 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 { + fn step_down(&self, step: Option, _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 { + fn step_up(&self, step: Option, _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 { + fn step_down(&self, step: Option, _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 { + fn step_up(&self, step: Option, _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 { #[prop_or_default] pub step: Option, + /// 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 ManagedField for NumberField { 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 ManagedField for NumberField { fn value_changed(&mut self, ctx: &super::ManagedFieldContext) { 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 ManagedField for NumberField { fn changed(&mut self, ctx: &ManagedFieldContext, 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 ManagedField for NumberField { 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 ManagedField for NumberField { 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 ManagedField for NumberField { 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