Alberto
Alberto

Reputation: 21

How can I format number shown in HTML to currency format, including the $ symbol and placing decimals with <sup></sup>?

I have a page with several HTML text strings with numbers, let's say one is 123.20. All of them are enclosed at third level in a div with the "money" class. I want to change all of them to the format $123.20 (the number is different for each of them) using JS.

I cannot include the "money" class to the any other div than the first shown below. I cannot format this into the backend (even if I would love to).

I don't know where to start from.

This is an example of the current HTML.

<div class="elementor-element elementor-element-11138f85 elementor-widget__width-auto money elementor-widget elementor-widget-text-editor" data-id="11138f85" data-element_type="widget" data-widget_type="text-editor.default">
  <div class="elementor-widget-container">
    <div class="elementor-text-editor elementor-clearfix">123.20</div>
  </div>
</div>

This is what I would need to get displayed:

<div class="elementor-element elementor-element-11138f85 elementor-widget__width-auto money elementor-widget elementor-widget-text-editor" data-id="11138f85" data-element_type="widget" data-widget_type="text-editor.default">
  <div class="elementor-widget-container">
    <div class="elementor-text-editor elementor-clearfix">$123<sup>.20</sup></div>
  </div>
</div>

Upvotes: 1

Views: 6247

Answers (3)

fruitloaf
fruitloaf

Reputation: 2892

for Euros:

var number = 1500;

let numCurrency = new Intl.NumberFormat('eu-EU', { style: 'currency', currency: 'EUR' }).format(number);

console.log(numCurrency);

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

Upvotes: 0

Abdulsamet Kurt
Abdulsamet Kurt

Reputation: 1141

Intl​.Number​Format - MDN

var number = 123456.789;

console.log(new Intl.NumberFormat('tr-TR', { style: 'currency', currency: 'TRY' }).format(number));

Output

₺123.456,79

Upvotes: 2

jeffjenx
jeffjenx

Reputation: 17457

Here is a sample using split()

// find all the elements with your `money` class
var elements = document.getElementsByClassName('money')

// loop through all the `money` elements
for (var i = 0; i < elements.length; i++) {
  // split the money value into two parts (before the decimal and after)
  var amounts = elements[i].innerHTML.split('.')

  // update the content to your formatted version
  elements[i].innerHTML = amounts[0] + '<sup>.' + amounts[1] + '</sup>'
}

Upvotes: 3

Related Questions