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>
2
Answers
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.
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: