Home > Mobile >  Round up the cents field in JavaScript
Round up the cents field in JavaScript

Time:12-08

Here is the situation, I'm entering a dollar amount within the text field something similar to the following code:

<input type="text" name="qtr-revenue-<?php echo $qtr ?>" id="qtr-revenue-<?php echo $qtr ?>" class="qtr-revenue editable" value="<?php echo App_Number::formatCurrency($qtrNumbers['Revenue'], 2, '', true, '') ?>" />

However, the following thing is happening, I'm able to properly format for example 9,000,000.90 with no issues, however, whenever I mistakenly enter 9,000,000.90000099323, it formats the number to 9,000,000.900,000,993,23

How do I properly format the dollar amount from 9,000,000.90000099323 to 9,000,000.90?

Here is the javascript code that formats the number right now.

$(this).val(function (index, value) {
    return value
        .replace(/[^-\d\.]/g, "")
        .replace(/\B(?=(\d{3}) (?!\d))/g, ",");
});

CodePudding user response:

You can try this approach. It's not supported in IE11 though. Also you can play around with different currencies and their formats.

Here is some guides: MDN Web Docs

const number = "9,000,000.90000099323".replace(/,/g, '');
console.log(new Intl.NumberFormat('en-CA', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(number));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Not an JS expert but I have a financial website and to make a number look like the following I use the code below 1,139,447,000

String(value).replace(/(.)(?=(\d{3}) $)/g,'$1,');

I believe you should be able to change the result by updating the regex in here

  • Related