有没有办法防止在使用Javascript array.map(Number)时丢弃零的行为?

时间:2018-01-21 12:11:54

标签: javascript arrays type-conversion numbers decimal

类型转换数组元素使用array.map(Number)将字符串形式化为Number。 我需要数字有2个小数点。我遇到的问题是array.map(Number)丢了零。 示例1:将字符串“10.50”转换为10.5 示例2:将字符串“29.10”转换为29.1

这是我的剧本:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>

        </title>
    </head>
    <body>
        <script type="text/javascript">
            var bills = [50.23, 19.12, 34.01,
                        100.11, 12.15, 9.90, 29.11, 12.99,
                        10.00, 99.22, 102.20, 100.10, 6.77, 2.22];
            console.log(bills);  // these are logged as numbers

            var billsTips = bills.map(function(num) {
                var num = num + num * .15;
                return  num.toFixed(2);
            });

            console.log(billsTips);  // these are logged as strings

            var totals=billsTips.map(Number);
            console.log(totals);             // these are logged as numbers with zeros dropped
            console.log (typeof(totals[8])); // no longer a string, is as type number
            console.log(totals[8]);  // I would like 11.5 to be 11.50

        </script>
    </body>
</html>

0 个答案:

没有答案