Skip to content

Commit

Permalink
float input, use toLocaleString instead of toString
Browse files Browse the repository at this point in the history
toLocalString never uses exponential notation, so it works
better with our current system:
- with the acceptValue regex, exponential notation is rejected
so the user can't edit the field at all anymore
- even if exponential notation was accepted, switching automatically from
plain to exponential or vice versa is hard to understand and predict because
the input changes a lot, eg 10000000000000 -> 1e22
- even if it could be implemented, cursor position preservation becomes
even more complex with exponential notation. Note: even with toLocaleString,
the cursor may jump with more than 15 digits when precision forces a change in
digits
  • Loading branch information
jonenst committed Nov 23, 2023
1 parent 4352bcf commit 13637ab
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/components/react-hook-form/numbers/float-input.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,18 @@ const FloatInput = (props) => {
if (tmp.endsWith('.') || tmp.endsWith('0')) {
return tmp;
}
return parseFloat(tmp) || null;

// toLocaleString never uses exponential notation unlike toString.
// Avoiding exponential notation makes in place normalizing of numbers
// after each keystroke less intrusive. Note: with 16+ digits, rounding
// due to precision still causes the cursor to jump at the end...
// This should be fixable with manual cursor handling if we need it.
return (
parseFloat(tmp).toLocaleString('en-US', {
maximumFractionDigits: 20,
useGrouping: false,
}) || null
);
};

return (
Expand Down

0 comments on commit 13637ab

Please sign in to comment.