In my project, I have to display the total of selected item in thousand separated format. I am using java script to find total of selected values. Now I have to display the result in Thousand deperated format (like 12,345.00). Here the function that I have used to do that.
<script language = "javascript">
function ThousandSeparator(decimalDigits,Value)
{
// Separator Length. Here this is thousand separator
var separatorLength = 3;
var OriginalValue=Value;
var TempValue = "" + OriginalValue;
var NewValue = "";
// Store digits after decimal
var pStr;
// store digits before decimal
var dStr;
// Add decimal point if it is not there
if (TempValue.indexOf(".")==-1){TempValue+="."}
dStr=TempValue.substr(0,TempValue.indexOf("."));
pStr=TempValue.substr(TempValue.indexOf("."))
// Add "0" for remaining digits after decimal point
while (pStr.length-1< decimalDigits){pStr+="0"}
if(pStr =='.') pStr ='';
if(dStr.length > separatorLength)
{
// Logic of separation
while( dStr.length > separatorLength)
{
NewValue = "," + dStr.substr(dStr.length - separatorLength) + NewValue;
dStr = dStr.substr(0,dStr.length - separatorLength);
}
NewValue = dStr + NewValue;
}
else
{
NewValue = dStr;
}
// Add decimal part
NewValue = NewValue + pStr;
// Show Final value
alert(NewValue);
}
</script>
Fig (1) Thousand Separator Function in Java Script
You just need to pass 2 parameters. Number of digits require after decimal point and value you want to conver in thousand seperated format.
Happy Programming !!
2 comments:
function addCommas( sValue )
{
var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
while(sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, '$1,$2');
}
return sValue;
}
Thanks for this code. Now testing it... g'bye!
Post a Comment