0

I need to amend the amount to add £ before the number and change it to two decimals i.e. £9.00

const data = [
  {
    title: 'Todo',
    amount: 9.99,
  },
  {
    title: 'In-Progress',
    amount: 4,
  },
  {
    title: 'Completed',
    amount: 10,
  },
  {
    title: 'Short',
    amount: 15.48,
  },
];

I can't work out how?

Dan
  • 1,565
  • 3
  • 23
  • 43
  • are you just asking how to read and set properties of objects inside an array? anyway in general `Number.toFixed(2)` [toFixed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) – Diego D Feb 03 '23 at 10:08
  • Does this answer your question? [Format number to always show 2 decimal places](https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places) – tevemadar Feb 03 '23 at 10:17

3 Answers3

1

You could do that, or you could use the Intl.NumberFormat to change it to currency on-the-fly. That way you get to keep your data neutral, and let the browser/JS handle the transformation only when it's needed.

const data=[{title:"Todo",amount:9.99},{title:"In-Progress",amount:4},{title:"Completed",amount:10},{title:"Short",amount:15.48}];

const style = { style: 'currency', currency: 'GBP' };

for (const obj of data) {
  const currency = new Intl.NumberFormat('en-GB', style).format(obj.amount);
  console.log(currency);
}

If you still want to change the data this method is still preferable. map over the data, destructure the amount from the object, and return a new object with the transformed amount.

const data=[{title:"Todo",amount:9.99},{title:"In-Progress",amount:4},{title:"Completed",amount:10},{title:"Short",amount:15.48}];

const style = { style: 'currency', currency: 'GBP' };

function toGBP(amount) {
  return new Intl.NumberFormat('en-GB', style).format(amount);
}

const out = data.map(obj => {
  const { amount, ...rest } = obj;
  return { ...rest, amount: toGBP(amount) };
});

console.log(out);

Additional documentation

Andy
  • 61,948
  • 13
  • 68
  • 95
0

Just map through it and use .toFixed(2) for the decimal.

const data = [
  {
    title: 'Todo',
    amount: 9.99,
  },
  {
    title: 'In-Progress',
    amount: 4,
  },
  {
    title: 'Completed',
    amount: 10,
  },
  {
    title: 'Short',
    amount: 15.48,
  },
];

const mapped = data.map((n) => { return {title: n.title, amount: `£${n.amount.toFixed(2)}`}});

console.log(mapped);
Adam Pearson
  • 304
  • 1
  • 7
0

You can use Number#toFixed(2) and Array#map() methods as follows:

const 
      data = [ { title: 'Todo', amount: 9.99, }, { title: 'In-Progress', amount: 4, }, { title: 'Completed', amount: 10, }, { title: 'Short', amount: 15.48 } ],
      
      out = data.map(({title,amount}) => ({title,amount:`£${amount.toFixed(2)}`}));
      
console.log( out );
PeterKA
  • 24,158
  • 5
  • 26
  • 48