Home > Software engineering >  Add comma separator for text with currency(USD) using js
Add comma separator for text with currency(USD) using js

Time:08-09

In the following example I want to make 16000.00 USD to 16,000.00 USD but I tried with toLocalString to add comma separator and bind the USD at last. But I couldn't make it.

Anyone help me to achieve this.

Actual Result: 16,000.00

Expected Result: 16,000.00 USD

var price = $("abbr").text()
var abbr_text = parseFloat(price)
result_ainp = abbr_text.toLocaleString(undefined, {minimumFractionDigits: 2})
console.log('result_ainp',result_ainp)
$("abbr").text(result_ainp)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<abbr>16000 USD</abbr>

CodePudding user response:

You can achieve this by splitting the string first, using split(), processing the number on its own, then putting the string back before assigning it to the element.

Note: the snippet below contains more things defined than it should be, but it's on purpose to showcase the result of each step.

Note: the snippet below also makes use of destructuring assignment and template literals.

const price = $("abbr").text();
const [amount, currency] = price.split(' ');
const parsedAmount = parseFloat(amount);
const processedAmount = parsedAmount.toLocaleString(
    undefined,
    { minimumFractionDigits: 2 }
);
const finalPrice = `${processedAmount} ${currency}`;
$("abbr").text(finalPrice);
console.log('result_ainp', finalPrice);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<abbr>16000 USD</abbr>

CodePudding user response:

This might be helpful:

JavaScript's Intl.NumberFormat() enables language-sensitive number formatting without the need for a third-party library.

Comprehensive docs on MDN for it: Link

Example:

new Intl.NumberFormat('en-US', { style: "currency", currency: "USD"}).format(123456.789) // '$123,456.79'

new Intl.NumberFormat('de-DE', { style: "currency", currency: "USD"}).format(123456.789) // '123.456,79 €'
  • Related