-2

My code

  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 ];

  var totals = bills.map(function(tip){
     tip += 15/100;
     tip = tip.toFixed(2);
     return tip;
  });
  console.log(totals);

RETURNS

  [ '50.38', '19.27', '34.16', '100.26', '12.30', '10.05', 
   '29.26', '13.14', '10.15', '99.37', '102.35', '100.25', '6.92', '2.37' ]

Now, How can i convert this string array into an numbers array like this

  [ 50.38,  19.27, 34.16, 100.26, 12.30, 10.05, 
   29.26, 13.14, 10.15, 99.37, 102.35, 100.25, 6.92, 2.37 ]
Parama Kar
  • 462
  • 3
  • 8
  • toFixed converts a number to a string – James Mar 12 '18 at 15:04
  • 1
    Possible duplicate of [What's the fastest way to convert String to Number in JavaScript?](https://stackoverflow.com/questions/12862624/whats-the-fastest-way-to-convert-string-to-number-in-javascript) – VtoCorleone Mar 12 '18 at 15:05
  • 1
    is the tip 15 %? or a fixed value, like 0.15 ? – Nina Scholz Mar 12 '18 at 15:06
  • This is kind of an X->Y question. You currently convert your array of numbers to strings via .toFixed. You could wait until you are about to display those numbers before using .toFixed, not halfway through a series of calculations, where you might still need the values to be Numbers for future operations. – James Mar 12 '18 at 15:12
  • remove `.toFixed(2)`. Like magic, they'll be numbers again. – Kevin B Mar 12 '18 at 20:35

2 Answers2

0

Coerce the return value to a Number, Replace

return tip;

with unary plus +

return +tip;

or Number constructor

return Number(tip);

You can shorten your code to

var totals = bills.map( tip => +( tip + 15/100 ).toFixed( 2 ) ); 
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
-1

You could loop through the array and use the parseFloat() function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

doublea
  • 447
  • 1
  • 4
  • 11