parseFloat Stops at the First Bad Character
Parse numeric strings with parseFloat and parseInt, which tolerate trailing garbage where Number() rejects it — choose deliberately per input source.
Code
const raw = "3.14rem";
// parseFloat 解析前缀、忽略尾部非数字
console.log(Number.parseFloat(raw)); // 3.14
console.log(Number.parseInt("12px")); // 12
// Number() 严格得多:整体必须是合法数字
console.log(Number("3.14"), Number(" 12 ")); // 3.14 12
console.log(Number("12px")); // NaN
// parseFloat 同样宽容空格但不认科学计数以外的其他进制
console.log(Number.parseFloat(" 2.5e2 ")); // 250
console.log(Number.parseInt("0x1f")); // 31(默认按 16 解析)
console.log(Number.parseInt("08", 10)); // 8:显式进制最稳
// NaN 要用 Number.isNaN 判断,=== 不行
const width = Number.parseFloat("42%");
console.log(width, Number.isNaN(Number.parseFloat("px")));
// 遇到第二个小数点即停
console.log(Number.parseFloat("12.5.3"));
// 四舍五入到样式常用精度
console.log(Math.round(Number.parseFloat(raw) * 10) / 10);Output
Captured from a sandboxed run of this snippet in the build pipeline.
3.14
12
3.14 12
NaN
250
31
8
42 true
12.5
3.1How it works
Everything operates on top-level bindings: raw, width.
Number.parseFloat("3.14rem") stops at the first bad character and returns 3.14, Number.parseInt("12px") returns 12, while Number("12px") is NaN — Number() parses the whole string or nothing. The edge cases are pinned in the later lines: parseInt("0x1f") honors the 0x prefix (31), parseInt("08", 10) needs the explicit radix to stay decimal, and parseFloat("12.5.3") stops at the second dot.
What to watch for
- The whole dependency story is the language version itself.
Core lines
const width = Number.parseFloat("42%");
const raw = "3.14rem";
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `raw`, `width`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.