How to insert commas in numbers in an html template? - javascript

I have an html template, I want to make a generalize function that itself finds all the numbers in my template and insert comma after every 3 digits. Currently I am using this function which may take some value as an input to convert it into comma separated form.
function commafy( num ) {
var str = num.toString().split('.');
if (str[0].length >= 5) {
str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
}
if (str[1] && str[1].length >= 5) {
str[1] = str[1].replace(/(\d{3})/g, '$1 ');
}
return str.join('.');
}
My template contains labels, tables & input fields.
Please help me how can I do that?

If the templates know where the numbers are, just put a class for them. After the template being rendered, select and change the numbers together. Note: there'is a jquery plugin called format_currency.
If the templates does NOT know, do it after render done:
$('#TEMPLATE_CONTAINER input,#TEMPLATE_CONTAINER label,#TEMPLATE_CONTAINER td').each(function(){
FORMAT($(this));//format only if $(this).text() is a number
})

Working Demo http://jsfiddle.net/cse_tushar/P3CSF/
you can use this awesome function for number formatting
e.g
var num=123456789.12345
num.formatMoney(5) //returns 123,456,789.12345
num.formatMoney(2) //returns 123,456,789.12
function code is here :-
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
console.log((123456789.12345).formatMoney(5, '.', ','));
console.log((123456789.12345).formatMoney(2));
if you want plugins :- Plugins

There are many ways:
You can wrap your money values inside a <span class='money'></span> span, and then using jQuery format those values, on DOM ready.
Using Angular JS, you can give your money values a directive, say ng-money and define that directive such that it formats the content of that span.
Third way is to send money values already commified (as you mentioned that :D ), and use them directly inside your template. Usually on server side, it's easier to format numbers and values.

I've a solution which probably works the way you want. This is only as far my understanding of the problem.
Here are few lines of code. The fiddle is also linked
var formatedNumbers=function(){
count=document.getElementsByTagName('input').length;
for(i=0;i<count;i++){
if(!isNaN(document.getElementsByTagName('input')[i].value) && document.getElementsByTagName('input')[i].value!=""){
document.getElementsByTagName('input')[i].value=formatNumber(document.getElementsByTagName('input')[i].value);
}
}
};

Related

Formatting a constantly changing number with commas

I am trying to make an increment/idle game that constantly has changing values in terms of money. I want to be able to separate large numbers using commas. E.g 1000 becomes 1,000 and so on, all while the value is till changing.
$<span id="money">0</span>
Above shows how I am using the span tag to call the money variable from the javascript. How would I make sure that this money variable stays formatted constantly even when changing?
Edit
function formatNumber(e){
var rex = /(^\d{2})|(\d{1,3})(?=\d{1,3}|$)/g,
val = this.value.replace(/^0+|\.|,/g,""),
res;
if (val.length) {
res = Array.prototype.reduce.call(val, (p,c) => c + p) // reverse the pure numbers string
.match(rex) // get groups in array
.reduce((p,c,i) => i - 1 ? p + "," + c : p + "." + c); // insert (.) and (,) accordingly
res += /\.|,/.test(res) ? "" : ".0"; // test if res has (.) or (,) in it
this.value = Array.prototype.reduce.call(res, (p,c) => c + p); // reverse the string and display
}
}
var mySpan = document.getElementById("money");
mySpan.addEventListener("change", formatNumber);
I have now implemented this code into my javascript but it still does not seem to be updating the variable.
Edit 2
function moneyClick(number){
money = money + number;
document.getElementById("money").innerHTML = money;
lifetimeearnings = lifetimeearnings + number;
document.getElementById("lifetimeearnings").innerHTML = lifetimeearnings;
};
Either update using some variation of what #redu pointed out whenever you calculate some changes to your money variable in the game's JavaScript, or use setInterval() to update it every 100 or so msec.
OK.. I was slightly wrong in my comment. As i understand the "change" event listener is blind to the changes at the child nodes like textContent. There is in fact this "DOMSubtreeModified" event listener that we may take use of. So;
function formatNumber(e) {
var rex = /(^\d{2})|(\d{1,3})(?=\d{1,3}|$)/g,
val = this.textContent.replace(/^0+|\.|,/g, ""),
res;
if (val.length) {
res = Array.prototype.reduce.call(val, (p, c) => c + p) // reverse the pure numbers string
.match(rex) // get groups in array
.reduce((p, c, i) => i - 1 ? p + "," + c : p + "." + c); // insert (.) and (,) accordingly
res += /\.|,/.test(res) ? "" : ".0"; // test if res has (.) or (,) in it
this.textContent = Array.prototype.reduce.call(res, (p, c) => c + p); // reverse the string and display
}
}
var mySpan = document.getElementById("money");
mySpan.addEventListener("DOMSubtreeModified", formatNumber);
for (var i = 0; i < 10; i++) {
setTimeout(_ => mySpan.textContent = Math.floor(Math.random() * 10000000), 1000 * i);
}
<span id="money">0</span>

Displaying current & total page number N(N)

I am new to Javascript,so forgive my silly mistakes in advance.
I have a requirement where I have to print current and total page number excluding even pages which are blank.
Example : For 5 page long document,it should display like:
1(3)
2(3)
3(3)
Any sort of info is welcome since I am in dire need of this code to work.
I have tried this but it doesn't work:
var current_page=0 ;
var total_pages=0;
if((current_page<total_pages)||(current_page=total_pages))
{
current_page++;
if(current_page % 2!==0)
{
total_pages++;
}
}
Also, this one too doesn't worked :(
var temp = (this.pageNum) + "(" + (this.numPages) + ")" ;
You have a logical error here:
current_page = total_pages // Note single = symbol between.
You are assigning instead of comparing. Please use == to compare:
current_page == total_pages
Or === for strict comparison as the type of both the variables is same.
Does that help?
function (totalPages, currentPage)
{
if (currentPage%2==1) return "";
var tp = parseInt(totalPages/2+1);
var cp = parseInt(currentPage/2+1);
return "" + cp + "(" + tp + ")";
}

Alternative to toLocaleString() for safari browser

I am using this code to convert number to string:
ProductsData[0]['price'].toLocaleString();
I am getting the expexted output:
8,499
But same code is not working for Safari.
Please give me suggestion on same.........
Although toLocaleString (without parameters) works in all mainstream browsers, it's behaviour is inconsistent from one browser to another, unfortunately.
If consistent date/time formatting is important, I'm afraid you will need to resort to building your own version of toLocaleString or working with a library. Here are a couple that may be worth investigating:
https://code.google.com/p/datejs/
https://github.com/jquery/globalize
I've encountered this issue today while working on a (almost complete) site which uses this function a lot and stumbled upon your question (Safari not showing any currency and/or thousands/decimal separators). I wrote a small override function to pop in and fix the toLocaleString to my needs (in Europe and euro's (€)).
Hope this helps anybody else encountering this same issue.
(function() {
Number.prototype._toLocaleString = Number.prototype.toLocaleString;
Number.prototype.toLocaleString = function(locales,options) {
if(options.style == "currency") { // only format currencies.
var prepend = "";
if(options.currency == "EUR") {
prepend = "\u20AC "; // unicode for euro.
}
var val = this;
val = val;
// check if the toLocaleString really does nothing (ie Safari)
var tempValue = val._toLocaleString(locales,options);
if(tempValue == val.toString()) { // "broken"
return prepend+val.formatMoney(2); // <-- our own formatting function.
} else {
return tempValue;
}
} else {
return this._toLocaleString(locales,options);
}
};
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "," : d,
t = t == undefined ? "." : t,
s = n < 0 ? "-" : "",
i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
// demonstration code
var amount = 1250.75;
var formattedAmount = amount.toLocaleString('nl-NL', {style:'currency',currency: 'EUR'});
console.log(formattedAmount);
})();
credits (and info about the "formatMoney") to https://stackoverflow.com/a/149099/2225737

Numbers in the form of 001

Is there a special name for numbers in the format of 001.
For example the number 20 would be 020 and 1 would be 001. Its hard to Google around when you don`t know somethings name! Since I am already wasting your guys time does any one know a function for changing numbers to this format.
I think this is usually called "padding" the number.
Its called left zero padded numbers.
It's called padding.
Well, if you're talking about that notation within the context of certain programming languages, 020 as opposed to 20 would be Octal rather than Decimal.
Otherwise, you're referring to padding.
A quick google search revealed this nice snippet of code for Number Padding:
http://sujithcjose.blogspot.com/2007/10/zero-padding-in-java-script-to-add.html
function zeroPad(num,count)
{
var numZeropad = num + '';
while(numZeropad.length < count) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}
You can use a simple function like:
function addZ(n) {
return (n<10? '00' : n<100? '0' : '') + n;
}
Or a more robust function that pads the left hand side with as many of whatever character you like, e.g.
function padLeft(n, c, len) {
var x = ('' + n).length;
x = (x < ++len)? new Array(len - x) : [];
return x.join(c) + n
}
Try this one:
Number.prototype.toMinLengthString = function (n) {
var isNegative = this < 0;
var number = isNegative ? -1 * this : this;
for (var i = number.toString().length; i < n; i++) {
number = '0' + number;
}
return (isNegative ? '-' : '') + number;
}

Adding extra zeros in front of a number using jQuery?

I have file that are uploaded which are formatted like so
MR 1
MR 2
MR 100
MR 200
MR 300
ETC.
What i need to do is add extra two 00s before anything before MR 10 and add one extra 0 before MR10-99
So files are formatted
MR 001
MR 010
MR 076
ETC.
Any help would be great!
Assuming you have those values stored in some strings, try this:
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
pad("3", 3); // => "003"
pad("123", 3); // => "123"
pad("1234", 3); // => "1234"
var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"
I have a potential solution which I guess is relevent, I posted about it here:
https://www.facebook.com/antimatterstudios/posts/10150752380719364
basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code
var d = new Date();
var h = ("0"+d.getHours()).slice(-2);
var m = ("0"+d.getMinutes()).slice(-2);
var s = ("0"+d.getSeconds()).slice(-2);
I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.
then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.
Note: see Update 2 if you are using latest ECMAScript...
Here a solution I liked for its simplicity from an answer to a similar question:
var n = 123
String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5); // returns 00123
UPDATE
As #RWC suggested you can wrap this of course nicely in a generic function like this:
function leftPad(value, length) {
return ('0'.repeat(length) + value).slice(-length);
}
leftPad(123, 5); // returns 00123
And for those who don't like the slice:
function leftPad(value, length) {
value = String(value);
length = length - value.length;
return ('0'.repeat(length) + value)
}
But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.
UPDATE 2
In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.
So with ES6 it became as simple as:
var n = '123';
n.padStart(5, '0'); // returns 00123
Note: #Sahbi is right, make sure you have a string otherwise calling padStart will throw a type error.
So in case the variable is or could be a number you should cast it to a string first:
String(n).padStart(5, '0');
function addLeadingZeros (n, length)
{
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}
//addLeadingZeros (1, 3) = "001"
//addLeadingZeros (12, 3) = "012"
//addLeadingZeros (123, 3) = "123"
This is the function that I generally use in my code to prepend zeros to a number or string.
The inputs are the string or number (str), and the desired length of the output (len).
var PrependZeros = function (str, len) {
if(typeof str === 'number' || Number(str)){
str = str.toString();
return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
return str;
}
};
Examples:
PrependZeros('MR 3',3); // MR 003
PrependZeros('MR 23',3); // MR 023
PrependZeros('MR 123',3); // MR 123
PrependZeros('foo bar 23',3); // foo bar 023
If you split on the space, you can add leading zeros using a simple function like:
function addZeros(n) {
return (n < 10)? '00' + n : (n < 100)? '0' + n : '' + n;
}
So you can test the length of the string and if it's less than 6, split on the space, add zeros to the number, then join it back together.
Or as a regular expression:
function addZeros(s) {
return s.replace(/ (\d$)/,' 00$1').replace(/ (\d\d)$/,' 0$1');
}
I'm sure someone can do it with one replace, not two.
Edit - examples
alert(addZeros('MR 3')); // MR 003
alert(addZeros('MR 23')); // MR 023
alert(addZeros('MR 123')); // MR 123
alert(addZeros('foo bar 23')); // foo bar 023
It will put one or two zeros infront of a number at the end of a string with a space in front of it. It doesn't care what bit before the space is.
Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)
function pad(str, new_length) {
('00000000000000000000000000000000000000000000000000' + str).
substr((50 + str.toString().length) - new_length, new_length)
}
I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:
function lpad(n, e, d) {
var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
return o; }
Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.
var str = "43215";
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
str = "0" + str;
}
console.log("After : \n string :"+str+"\n Length :"+str.length);
It worked for me !
To increase the zeroes, update the 'max' variable
Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:
str could be a number or a string.
formatting("hi",3);
function formatting(str,len)
{
return ("000000"+str).slice(-len);
}
Add more zeros if needs large digits
In simple terms we can written as follows,
for(var i=1;i<=31;i++)
i=(i<10) ? '0'+i : i;
//Because most of the time we need this for day, month or amount matters.
Know this is an old post, but here's another short, effective way:
edit: dur. if num isn't string, you'd add:
len -= String(num).length;
else, it's all good
function addLeadingZeros(sNum, len) {
len -= sNum.length;
while (len--) sNum = '0' + sNum;
return sNum;
}
Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.
var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);
By adding 100 to the number, then run a substring function from index 1 to the last position in right.
var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);
console.log(month,day);
you will got this result from the date of 2020-11-3
11,03
I hope the answer is useful

Categories

Resources