C's stdlib.strtod in TypeScript

✓ Verified: C 23
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { strtod } from 'locutus/c/stdlib/strtod'.

Or with CommonJS: const { strtod } = require('locutus/c/stdlib/strtod')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1strtod('3.14')3.14
2strtod(' -2.5e2xyz')-250
3strtod('abc')0

C types and TypeScript/JavaScript

C is statically typed while TypeScript/JavaScript is dynamically typed. Locutus C functions accept TypeScript/JavaScript's flexible types but are only parity-verified for inputs that would be valid in C.

For example, abs() in TypeScript/JavaScript accepts floats (like C's fabs()) and handles strings gracefully, but only integer inputs are verified against native C. This pragmatic approach gives you the expected C behavior for valid inputs while leveraging TypeScript/JavaScript's flexibility for edge cases.

Notes

  • Parses a floating-point number from the start of the string.

  • Stops at the first invalid trailing character, similar to C strtod.

Here's what our current TypeScript equivalent to C's strtod found in the stdlib.h header file looks like.

export function strtod(str: string): number {
// discuss at: https://locutus.io/c/stdlib/strtod/
// parity verified: C 23
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Parses a floating-point number from the start of the string.
// note 2: Stops at the first invalid trailing character, similar to C strtod.
// example 1: strtod('3.14')
// returns 1: 3.14
// example 2: strtod(' -2.5e2xyz')
// returns 2: -250
// example 3: strtod('abc')
// returns 3: 0

const input = String(str).replace(/^\s+/, '')
const match = input.match(/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/)
if (!match || !match[0]) {
return 0
}

const parsed = Number.parseFloat(match[0])
return Number.isNaN(parsed) ? 0 : parsed
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 20 C functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More C stdlib functions


Star