So German decimal numbers use a decimal comma. When formatting we also use the period for grouping digits. So the number 10000.45 would be formatted as 10.000,45.
Now I would like to have an input-field (numeric or text) where you can type the "german" way using periods and commas. However, I want to also keep track of a "normal" numeric value in JavaScript.
Converting a numeric value to a german-formatted value is easy with
number.toLocaleString("de-DE", { maxFractionDigits: 2 })
But how do I get this backformatted to a decimal number? Because when I display the german-formatted value like "7,20" I append to the end right?
Here is a svelte-repl with an initial try that looks like this: https://svelte.dev/repl/fabd0a80f4ee49509cd875c0175bcf22?version=4.0.1
<script>
let numericValue = 0;
let formattedValue = '';
function formatNumber(value) {
return value.toLocaleString("de", {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
}
function handleInput(event) {
// Remove dots as thousand separators and convert decimal comma to dot
const inputValue = event.target.value.replace(/\./g, '').replace(/,/g, '.');
// Update numericValue with parsed float
numericValue = parseFloat(inputValue);
// Update formattedValue for display
formattedValue = formatNumber(numericValue);
}
</script>
<input type="text" value={formattedValue} on:input={handleInput} />
<p>Numeric value: {numericValue}</p>
Ideally, I would like to have the displayed, formatted value on the input-event. But it can also be on the on-change event. Or even using a button next to it or something. I'd be grateful for any tip!:)
I would recommend just not messing with the user input, i.e. not setting formattedValue
in the input
event handler. If you want to format the number nicely, do it the first time the component is shown and on blur
to prevent interfering with the user's intentions.
If you really want to strictly prescribe a certain format while the user is typing that is non trivial because the cursor position, number sign, clearing the value and other things have to taken into account. There are also libraries for that, e.g. imask
.