Svelte inconsistency in binding

Viewed 264

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?

2 Answers

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" />

No inconsistency: input values are strings by default. Svelte won't know that you are expecting a number back, so binding a converts it to a string after an update (as @ray pointed out, toLocaleString won't produce the same result on a string). You can tell Svelte to expect a number by specifying type="number" on your input:

<script>
    let a = 1000000;
</script>

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

<p>Formatted <strong>a</strong> is {a.toLocaleString("en-US")} </p>

REPL

Related