Esquirish
Esquirish

Reputation: 195

Currency formatting of JavaScript created numbers

I have a basic page with a cart-like system written in JS.

I'd like to format the numbers shown as a currency, using Intl.NumberFormat to make the prices readable according to the users locale if possible.

Having a very basic knowledge of JS, i have made various attempts without success, partial code looks like this:

$('.price').html(set_price.toFixed(2));

I have attempted to modify the above code to this:

$('.price').html(Intl.NumberFormat('de-DE').format(parseFloat(set_price.toFixed(2))));

But it doesn't work, because the number produced by the above code is used for other calculations in the page (for example, if quantity changes it add/substracts the number, resulting in calculation errors.)

The totals are shown in the front end inside a div such as this one:

<div class="price">0</div>

Where it dinamically updates the number as items are added/substracted.

Is there a way to format the number shown, without obstructing its calculation capabilities?

Upvotes: 0

Views: 260

Answers (1)

OpherV
OpherV

Reputation: 6947

It's unclear from your question, but are you trying to use the formatted value for further calculation? If so - then this is definitely a code smell and should be avoided.

A better approach would be to save the actual number in a data model (fancy name for in-memory variable) and only show the formatted number in presentation (actual rendered HTML). That way you never "obstruct its calculation capabilities".

e.g.

let myValue = x;
let displayValue = Intl.NumberFormat('de-DE').format(parseFloat(myValue.toFixed(2)))
$('.price').html(displayValue);

Upvotes: 1

Related Questions