0 day streak
javascript / beginner
Snippet

Sanitizing and Converting Form Inputs to Numeric Datatypes in Svelte

HTML inputs typically deliver user values as strings. Using `Number.parseFloat()` with fallback default operators ensures data type safety and guards against NaN values before performing reactive arithmetic calculations.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
<script>
let rawInput = "0";
$: parsedNumber = Number.parseFloat(rawInput) || 0;
$: doubledValue = parsedNumber * 2;
</script>
<label for="numeric-input">Enter amount:</label>
<input id="numeric-input" type="text" bind:value={rawInput} />
<p>Parsed Number: {parsedNumber}</p>
<p>Doubled Result: {doubledValue}</p>
svelte
Breakdown
1
let rawInput = "0";
Initializes a string state variable bound to the raw form input field.
2
$: parsedNumber = Number.parseFloat(rawInput) || 0;
Reactively parses the input string into a floating-point number, defaulting to 0 if parsing produces NaN.
3
$: doubledValue = parsedNumber * 2;
Performs mathematical arithmetic on the sanitized numeric datatype whenever parsedNumber changes.
4
<input id="numeric-input" type="text" bind:value={rawInput} />
Binds the text field value two-way to the rawInput variable in Svelte.