Reputation: 105
I have code :
function money_format(number) {
//if (isNaN(number)) return "";
var str = new String(number);
var result = "" , len = str.length;
for(var i=len-1;i>=0;i--) {
if ((i+1)%3 == 0 && i+1!= len) {
result += ",";
}
result += str.charAt(len-1-i);
}
return result;
}
Event:
$("#number").keyup(function() {
var tot = 0;
tot = $(this).val().substr(0).replace(/\./g,'')
$(this).val(money_format(tot));
$("#msg").html(tot);
});
Se my jsfiddle :http://jsfiddle.net/bx5bu3j0/
How to remove the last coma??
like : 1.000.000,01
Upvotes: 0
Views: 242
Reputation: 104780
if you use a string replace that stops when it reaches any non-digit you can add commas to a string with a decimal-
function addCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
var n=123456789.091;
addCommas(n)
/* returned value: (String)
123,456,789.091
*/
Upvotes: 1
Reputation: 27855
You can use lastIndexOf
and find the index of the comma you want to remove and then use substr
to remove it from the string.
Here is a sample fiddle
.
function money_format(number) {
var str = new String(number);
var index = str.split('').lastIndexOf(",");
/* remove if comma found */
if(index != -1) {
str = str.substr(0, index) + str.substr(index+1);
}
return str;
}
alert(money_format("1.000.000,01"));
Upvotes: 0
Reputation: 253318
I'd suggest simply avoiding working on the float-part of the number:
function money_format(number) {
// use toString() to create a string,
// split the string to an integer and float portion:
var numbers = number.toString().split('.'),
integerPortion = numbers[0],
// if there is a float portion, we'll use it, otherwise set it to false:
floatPortion = numbers[1] ? numbers[1] : false,
result = "",
len = integerPortion.length;
for (var i = len - 1; i >= 0; i--) {
if ((i + 1) % 3 === 0 && i + 1 != len) {
result += ",";
}
result += integerPortion.charAt(len - 1 - i);
}
// return the concatenated 'result' with either the float portion (if there is/was one)
// or an empty string, if there was not:
return result + (floatPortion ? '.' + floatPortion : '');
}
console.log(money_format(12345678.98));
Upvotes: 1