javascript / beginner
Snippet
Handling Numeric Datatypes in Input Bindings
HTML input elements produce string values by default. In JavaScript and Svelte, handling numeric operations reliably requires explicit type conversion using functions like parseFloat() to prevent unintentional string concatenation and NaN errors.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
<script>let rawPrice = '19.99';let taxRate = 0.19;function calculateTotal(priceStr, tax) {const parsedPrice = parseFloat(priceStr) || 0;return Number((parsedPrice * (1 + tax)).toFixed(2));}</script><input type="text" bind:value={rawPrice} placeholder="Enter price" /><p>Total with Tax: {calculateTotal(rawPrice, taxRate)}</p>
svelte
Breakdown
1
const parsedPrice = parseFloat(priceStr) || 0;
Converts the string datatype to a floating-point number and provides a fallback value of 0 if parsing fails.
2
return Number((parsedPrice * (1 + tax)).toFixed(2));
Calculates the total, formats it to two decimal places, and converts the resulting string back into a primitive number.