Adding Two Decimal Places using JavaScript

浪子不回头ぞ 提交于 2019-12-02 08:22:37

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.

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

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.

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