Home > front end >  Represent number as currenct from paragraph
Represent number as currenct from paragraph

Time:02-12

On my web page I have an paragraph which looks like this:

<p  id="cost"><strong>Cost [Euro]: </strong>1000000</p>

Number is always something else (which I read from db and represent using Django forms) and I would like to represent it as currency (in this case 1.000.000). I tried to get the value with:

function on_load() {
  var a = document.getElementById('cost').value;
  console.log(a)
}
on_load();
<p  id="cost"><strong>Cost [Euro]: </strong>1000000</p>

but Console output is: 'undefined'. When I get value, I'll use something like

(12345.67).toFixed(2).replace(/\d(?=(\d{3}) \.)/g, '$&,');  // 12,345.67

To convert to currency.

CodePudding user response:

p does not have a value attribute. You can do this to get and format the number using intl number format

function on_load() {
  var a = document.querySelector('#cost').childNodes[1].textContent;
  console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(a))
}
on_load();
<p  id="cost"><strong>Cost [Euro]: </strong>1000000</p>

  • Related