I got requirement of the java-script Number formatting like below
I need one function its having 2 parameters like
var number = 1000;
var format = #,###.0; //or #,### ;
function ConvertNumber(number, format){
// this function need to return 1,000.0 if format is #,###.0
// this function need to return 1,000 if format is #,###
}
can anyone having this kind of function? your help is really appreciated thanks
The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in the above syntax using the '. ' operator.
The toString() method in Javascript is used with a number and converts the number to a string. It is used to return a string representing the specified Number object. The toString() method is used with a number num as shown in the above syntax using the '. ' operator.
In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.
The Number() method converts a value to a number.
You can se the NumberFormatter plug-in from JQuery.
Here's an example of how you'd use this plugin.
$("#salary").blur(function(){
$(this).format({format:"#,###.00", locale:"de"});
});
check this function...
var number = 1000; // int or float or string
var format = '#,###.0'; // you can put any format that you want... only string
function ConvertNumber(number, format){
var tail=format.lastIndexOf('.');number=number.toString();
tail=tail>-1?format.substr(tail):'';
if(tail.length>0){if(tail.charAt(1)=='#'){
tail=number.substr(number.lastIndexOf('.'),tail.length);
}}
number=number.replace(/\..*|[^0-9]/g,'').split('');
format=format.replace(/\..*/g,'').split('');
for(var i=format.length-1;i>-1;i--){
if(format[i]=='#'){format[i]=number.pop()}
}
return number.join('')+format.join('')+tail;
}
// Examples
// ConvertNumber(1234,'#,###') === 1,234
// ConvertNumber(1234,'#,###.00') === 1,234.00
// ConvertNumber(1234,',###.00') === 1,234.00
// ConvertNumber(1234.4575,',###.##') === 1,234.45
// ConvertNumber(1234567890.4575,',###,###,###.##') === 1,234,567,890.45
// ConvertNumber(123.4575,',#,#.##') === 1,2,3.45
// ConvertNumber(123456.4575,'-#-#.##') === 1234-5-6.45
// ConvertNumber(1234567.4575,' ## ###.##') === 12 34 567.45
hope this function will be very helpful for you and them who have the same problem... best of luck...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With