I have been working on a project and found an error with a JS message in the UI. The number is not being rounded before being displayed. I don't know JS very well however, I did try Math.round(num * 100) / 100
this did not work.
Any support with this would be great.
if($change_return_val != "0.00"){
// confirm('Oops amount is over.');
// calculate_balance_due();
swal({
title: "Change: £" $change_return_val,
text: "Your change return value is: £" $change_return_val,
})
}
CodePudding user response:
When converting a number
to a string
with a specified number of floating points, as @Ameer has said in a comment the toFixed
function is the typical way to go. However, for the specific task of displaying a number
as currency, you may want to consider using toLocaleString
instead.
For example, this converts the number into British English style, specifically as the currency of Great British Pounds:
const numberRaw = 123.456789;
const numberCurrency = numberRaw.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' });
console.log(numberCurrency);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
This method is also particularly useful if you have to deal with many locales, some of which may display numbers in quite different ways such as '1.234,57'
.