Search code examples
svelte-3

Svelte inconsistency in binding


I'm new to Svelte and was working with bindings.

Here's my code:

REPL

test.svelte

<script>
    let a = 1000000;
    let b = "ABCDeFgH";
</script>

A: <input bind:value={a} />
<br><br>
B: <input bind:value={b} />
<br>
<!-- works only on first run -->
<p>Formatted <strong>a</strong> is {a.toLocaleString("en-US")} </p>

<!-- works on update -->
<p>Formatted <strong>b</strong> is {b.toLowerCase()}</p>

The toLocaleString() method on a works on the first load but does not format the output (with commas) when updating the number using the input box during runtime.

However, the toLowerCase() seems to work fine even with updates to b during runtime.

What am I missing here?


Solution

  • Initially it's a number: 100000, but the input value is a string ("100000"), and strings get different behavior from toLocaleString. You could run it through parseInt or parseFloat, Number or whatever to convert it back:

    console.log((100000).toLocaleString('en-US'));
    console.log(("100000").toLocaleString('en-US'));
    console.log((Number("100000")).toLocaleString('en-US'));

    Or better yet, as Connor points out, just set the input type to "number":

    <input bind:value={a} type="number" />