首页 > 解决方案 > How to remove scientific exponent of a number?

问题描述

Typescript is giving TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))

let [ , num ] = hiResNum.toString().match(/^([+-]?[0-9]+[.]?[0-9]*)(e[+-]?[0-9]+)?$/);
num = parseFloat(num).toFixed(digits);

let num: any Type 'RegExpMatchArray | null' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)

How should I separate the scientific notation part of a number?

标签: typescript

解决方案


问题是String.match函数可以返回Array | null并且null不可迭代。所以,你需要知道它r是否为空;那么你可以使用r[1].

const r = hiResNum.toString().match(/^([+-]?[0-9]+[.]?[0-9]*)(e[+-]?[0-9]+)?$/);
if (r && r.length > 1) {
    num = parseFloat(r[1]).toFixed(digits);
}

推荐阅读