HenryEx icon

parseFormattedNumber

HenryEx | PRO | 05/18/26 04:56:32 PM UTC | 0 ⭐ | 10677 👁️ | Never ⏰ | []
JavaScript |

840 B

|

None

|

0 👍

/

0 👎

/** Extracts the first number formatted by ns.format.number() in a string.
 * @param {string} s String containing a formatted number
 * @returns {number} number */
function parseFormattedNumber(s) {
    if (typeof s !== "string") {ns.print("WARN: parseFormattedNumber: invalid type for input " + s); return NaN;}
    const [  // Ex.: "Gained $250.000m"
        num,   // "250.000m"
        base,  // "250.000"
        suffix // "m"
    ] = s.match(/(-?\d+(?:[\.,]\d{1,5})?)(e\d+|[kmbtqQsSon])?/);
 
    if (!num || !base) {ns.print("WARN: parseFormattedNumber: no valid number found for input " + s); return NaN;}
    
    const numSuffixList = ["", "k", "m", "b", "t", "q", "Q", "s", "S", "o", "n"];
    let exp = suffix ?? "";
    if (suffix && numSuffixList.includes(suffix)) {
        exp = "e" + (numSuffixList.indexOf(suffix) * 3);
    }
    return parseFloat(base.replace(",",".") + exp);
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎