Skip to content

parseInt is not strange #25

@cD1rtX3

Description

@cD1rtX3

parseInt only works on strings. When it encounters a number, it has to cast it to a string to work on it. 0.0000005 casts to a string as '5e-7', and so:

  1. parseInt encounters the '5' and writes it down.
  2. parseInt encounters the 'e' and quits, returning 5.

You could say the same thing about C:

constexpr double d = 5e-7;

char str[snprintf(nullptr, 0, "%lg", d)]; // Makes a buffer big enough
sprintf(str, "%lg", d); // Puts "5e-07" into `str`

const long int l = atol(str);
// `l` is now 5 !???!?!?!?!????!???!1/1/1/1//

You could also say the same about any other language with a parseInt-esque function that works similarly.

Everything is unexpected when you don't understand things.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions