0

Type casting array elements form string to Number using array.map(Number). I need the numbers to have 2 decimal points. Problem I am having is array.map(Number) drops zeros. example 1: converts the string “10.50” to 10.5 example 2: converts the string “29.10” to 29.1

Here is my script:

<!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>
Learn2Earn
  • 33
  • 1
  • 12
  • Tried anything other than tfixed? – zabusa Jan 21 '18 at 13:24
  • Did you see this question https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places – nitte93 Jan 21 '18 at 13:26
  • No. I have not. Pretty sure math.round won't help. Any suggestions? – Learn2Earn Jan 21 '18 at 13:26
  • After looking at the question you refferenced, I see this is changing innerHTML of spans. How would I apply this method to change the value of the array elements? I tried the following two ways, but not able to get desired result. var num = parseFloat(Math.round(num * 100) / 100).toFixed(2); return parseFloat(Math.round(num * 100) / 100).toFixed(2); – Learn2Earn Jan 21 '18 at 14:01

0 Answers0