Re: [PATCH v5 2/7] lib: kstrtox: round to nearest, ties to even in kstrto[u]dec64()

From: Rodrigo Alencar

Date: Wed Nov 04 2026 - 04:11:33 EST


On 03/11/26 19:55, Andy Shevchenko wrote:
> On Mon, Nov 02, 2026 at 07:41:00AM -0300, Rodrigo Alencar via B4 Relay wrote:
>
> > kstrtoudec64() and kstrtodec64() drop the digits beyond the requested
> > scale, which truncates the result toward zero. The error is up to one
> > unit in the last place and is always in the same direction.
> >
> > This is easy to hit with values produced by userspace floating point
> > formatting. Printing 0.3 with "%.17g" gives "0.29999999999999999",
> > which is parsed as 299999 with a scale of 6 instead of 300000. With E
> > notation a negative exponent can also drop integer digits, so "19e-1"
> > with a scale of 0 gives 1 instead of 2.
>
> To avoid unneeded brain work it would be nice to add an example for negative
> input, like -19e-01. And I hope (and it seems the case) we have test cases
> for that.

We do have the tests:

/* E notation: negative exponent rounds integer digits */
{"-27e-4", 3, -3LL},
{"-125e-1", 0, -12LL},
{"-135e-1", 0, -14LL},

>
> > Round the result to nearest instead, with ties to even. This is the
> > IEEE 754 default rounding mode, as used by strtod() and printf(), and it
> > does not bias results in either direction. The first discarded digit is
> > known from where parsing stopped, so no extra pass over the string is
> > needed: the remaining digits are only checked when the first discarded
> > digit is a 5. Since round-half-even is symmetric, kstrtodec64() keeps
> > rounding the magnitude and negates it.
> >
> > Inputs that fit within the scale are parsed exactly as before. An input
> > that rounds up past the type limit, such as "18446744073.7095516155"
> > with a scale of 9, now returns -ERANGE.
> >
> > Update the existing truncation test cases and add cases for ties and
> > for rounding at the type limits.

--
Kind regards,

Rodrigo Alencar