0

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

The number produced by the line i posted is shown directly in the html DIV, when another item is added to the basket its number (price) is added to that first number and so on. That is why the formatted output works correctly only in the first instance (when the item is first added)
@Esquirish In that case I would keep an in-memory tally of the added numbers, and format/present that tally instead. Or if that doesn't work for you product for some reason, keep an array of the original item values and re-calculate on item add.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.