javascriptparsefloat

Javascript parseFloat with different ExponentIndicator


I want to parse the following string: -3.755512109246D2 using javascript. Please notice that this format uses D as exponent indicator instead of the usual e or E.

parseFloat("-3.755512109246D2")

will ignore the last part (D2) and return -3.755512109246.

Reading the spec I see that only e and E is used as the ExponentIndicator and from a quick search it seems that these core functions are actually written in C++.

What are my options here? Take into account that I am parsing big files that will contain numbers with different formats, sometimes they will have an exponent, that exponent could be e, E, d and D.

If my only way is to rewrite parseFloat so now it treats the same way D and d as E what would be an efficient implementation?

My first bet would be something like:

var str ="-3.755512109246D2";
for(var i = 0; i < str.length; i++)
{
    if(str[i] == 'd' || str[i] == 'D')
    {
        str[i] = 'E';
        break;
    }
}
var result = parseFloat(str);

Is there a better way?


Solution

  • You can use replace with a regular expression to replace a d or D with e, then Number instead of parseFloat to make sure the entire string is interpreted as a number and not just cut off at the first invalid part:

    var result = Number(str.replace(/d/i, "e"));
    

    /d/i matches the first ā€œdā€ ASCII-case-insensitively.