Adding Two Decimal Places using JavaScript

徘徊边缘 提交于 2019-12-02 16:27:57

问题


Good day Everyone!

I want to know how to return the output with two decimal places. Instead of 10,000 I want it to return 10,000.00. Also I already put .toFixed(2) but it's not working.

When the amount has decimal number other than zero, the values appear on the printout, but when the decimal number has a zero value, the Zeros won't appear on the printout.

Also, I have added a value of Wtax that was pulled-out on a "Bill Credit" Transaction.

Output:


回答1:


Numeral.js - is a library that you can use for number formatting. With that you can format your number as follows:

numeral(10000).format('$0,0.00');

Hope this will help you.




回答2:


You can try this

var x = 1000;       // Raw input 
x.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')  //returns you 1,000.00

Alternately you can use Netsuite's currency function too

nlapiFormatCurrency('1000');   // returns you 1,000.00
nlapiFormatCurrency('1000.98');   // returns you 1,000.98



回答3:


You might consider below code. It can round off decimal values based on the decimal places.
This also addresses the issue when rounding off negative values by getting first the absolute value before rounding it off. Without doing that, you will have the following results which the 2nd sample is incorrect.

function roundDecimal(decimalNumber, decimalPlace)
{
//this is to make sure the rounding off is correct even if the decimal is equal to -0.995
var bIsNegative = false;
if (decimalNumber < 0)
{
    decimalNumber = Math.abs(decimalNumber);
    bIsNegative = true;
}
var fReturn = 0.00;
(decimalPlace == null || decimalPlace == '') ? 0 : decimalPlace;

var multiplierDivisor = Math.pow(10, decimalPlace);
fReturn = Math.round((parseFloat(decimalNumber) * multiplierDivisor).toFixed(decimalPlace)) / multiplierDivisor;

fReturn = (bIsNegative) ? (fReturn * -1) : fReturn;
fReturn = fReturn.toFixed(decimalPlace)

return fReturn;
}


Below are the test sample

And this test sample after addressing the issue for negative values.



来源:https://stackoverflow.com/questions/37694286/adding-two-decimal-places-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!