Home  >  Q&A  >  body text

Display html-Input-value as a number in german format when input changes while tracking decimal numbers

So German decimal numbers use decimal commas. When formatting, we also use periods to group numbers. So the number 10000.45 will be formatted as 10.000,45.

Now I want an input field (number or text) where you can enter the "German" way using periods and commas. However, I also want to track "normal" values ​​in JavaScript.

Use the following command to easily convert a numerical value to a value in German format

number.toLocaleString("de-DE", { maxFractionDigits: 2 })

But how to restore it to decimal number? Because when I display a value in german format like "7,20" I append to the end, right?

This is a preliminary attempt at svelte-repl, as shown below: 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 display the formatted value on the input event. But it can also appear on on-change events. Or even use the button on the side or something. Any tips would be greatly appreciated! :)

P粉615886660P粉615886660403 days ago695

reply all(1)I'll reply

  • P粉127901279

    P粉1279012792023-09-13 11:10:53

    I recommend not messing with user input, i.e. not setting formattedValue in the input event handler. If you want to format numbers nicely, do this when the component is first shown, and do it on Blur to prevent interfering with the user's intent.

    If you really want to enforce a certain format when the user enters it, it's not trivial because cursor position, number signs, clear values, and other factors must be taken into account. There are also libraries that can achieve this, such as imask.

    reply
    0
  • Cancelreply