JavaScript Convert String to Decimal: Examples and Tips
To convert a string to a decimal number in JavaScript, use Number() when the whole string should represent a number, or parseFloat() when you want to read a decimal value from the start of a string. For example, Number("12.75") returns the number 12.75; validate the result with Number.isNaN() or Number.isFinite() when the input may be invalid.
What “decimal” means in JavaScript
JavaScript does not have a separate everyday “decimal” type for values such as prices or measurements. Its standard numeric type is Number, which represents numbers using IEEE 754 double-precision binary floating-point. A decimal-looking value such as 12.75 is therefore a JavaScript number, not a string, after conversion.
The conversion function does not determine how many digits appear when a value is displayed. For example, converting "12.750" produces the numeric value 12.75; trailing zeros belong to formatting, not to the number itself. If you need exact decimal arithmetic for financial or other precision-sensitive work, ordinary floating-point calculations may need special handling or a decimal arithmetic library.
Convert a complete string with Number()
Number() is usually the clearest choice when the input is supposed to contain one complete numeric value. It accepts decimal notation, signs, and exponent notation, and converts surrounding whitespace away:
const text = " -18.625 ";
const value = Number(text);
console.log(value); // -18.625
console.log(typeof value); // "number"
Unlike a function that reads only a numeric prefix, Number() rejects extra non-whitespace text. For example, Number("12.5kg") returns NaN. That strict behavior is useful for form fields where the entire entry must be numeric.
Some less obvious conversions are worth knowing: Number("") and Number(" ") both return 0, while Number("1e3") returns 1000. If an empty field should count as missing rather than zero, check for an empty string before converting it.
When parseFloat() is the better fit
parseFloat() reads a decimal number from the beginning of a string and stops when it reaches a character that cannot continue that number:
parseFloat("12.75"); // 12.75
parseFloat("12.75px"); // 12.75
parseFloat("-0.5 units"); // -0.5
This can be convenient when parsing a value that deliberately has a suffix, but it can also hide bad input. If a user types "12.75abc", parseFloat() still returns 12.75. Use it only when accepting a numeric prefix is intended; otherwise prefer Number() and reject the whole malformed string.
parseFloat() returns NaN if the first non-whitespace character cannot begin a number. It recognizes decimal and exponent notation, such as ".25" and "2.5e2". It does not interpret commas as decimal separators: parseFloat("1,25") returns 1, not 1.25.
Validate input before using the result
A conversion can produce a number, NaN (“not a number”), or an infinite value. Check the converted result before calculations or display:
function readDecimal(text) {
if (text.trim() === "") {
return null; // Treat blank input as missing
}
const value = Number(text);
return Number.isFinite(value) ? value : null;
}
const result = readDecimal("23.4");
if (result !== null) {
console.log(result * 2); // 46.8
}
Number.isNaN(value) checks specifically for NaN. Number.isFinite(value) accepts ordinary finite numbers and rejects both NaN and positive or negative infinity, making it a useful general check for values that must be usable in typical arithmetic. These methods do not coerce strings themselves, so convert first.
For browser forms, input elements commonly expose their contents through a string-valued property. Read that string, decide how blanks and invalid entries should be handled, convert it, and then validate it. Do not assume that a field’s visual appearance guarantees valid numeric input.
Common conversion mistakes
- Using
parseInt()for decimals:parseInt("8.9", 10)returns8, because it parses an integer. UseNumber()orparseFloat()when fractional values matter. - Assuming every conversion fails the same way:
Number("8.9kg")returnsNaN, whileparseFloat("8.9kg")returns8.9. - Passing commas as decimal points: JavaScript’s standard numeric conversion expects a period as the decimal separator. A locale-formatted string such as
"1,25"needs deliberate locale-aware parsing; replacing punctuation blindly can misread thousands separators. - Confusing conversion with rounding:
Number("1.239")preserves the numeric value; it does not round to two decimal places. Formatting can control displayed digits, but formatting often returns a string. - Expecting exact decimal arithmetic: binary floating-point can produce results such as
0.1 + 0.2being slightly different from0.3. Rounding for display does not change the underlying representation.
Choosing a conversion method
Choose based on the rules for the input, not just on which function is shorter:
- Use
Number(text)when the complete trimmed string must be a valid number. - Use
parseFloat(text)when parsing a numeric prefix is intentional, such as reading a number followed by a known unit suffix. - Use
parseInt(text, 10)only when you want an integer; the second argument explicitly sets the radix to base 10.
For a unit-bearing value, it is often safer to parse the number and validate the unit separately rather than accepting any suffix. For example, a program can match a permitted numeric format, convert its numeric portion, and then check whether the remaining text is exactly an allowed unit. This prevents unexpected trailing characters from being silently ignored.
Frequently Asked Questions
How do I convert a string to a decimal in JavaScript?
Use Number("3.14") to convert the complete string to the number 3.14. Check that the result is finite if the input may be invalid.
Is parseFloat or Number better for decimal strings?
Use Number() if the whole string must be numeric. Use parseFloat() only if accepting a numeric prefix followed by other characters is appropriate.
Why does Number return zero for an empty string?
JavaScript converts an empty or whitespace-only string to 0. Check whether the original string is blank before calling Number() if blank input should be treated as missing.
How can I check whether a converted value is valid?
After conversion, use Number.isFinite(value) to ensure it is a finite number. It returns false for NaN and infinities.
How do I keep two decimal places?
Use value.toFixed(2) to create a string formatted with two digits after the decimal point. It formats the display; it does not make the underlying JavaScript number an exact decimal value.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.