javascript timer with comma [duplicate] - javascript

This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 9 years ago.
I want to display the dollar timer which goes from 1 to 2500. When the timer increases to 1000, I want to display it as $1,000 instead of $1000. I want commas in thousands place.Could someone help me with this JavaScript.
Thanks.

You could easily do this with a regular expression.
var friendlyNum = (num + "").replace(/^(\d)(\d{3})$/, "$1,$2");
Note that this will only handle 1000 places.
How it works is an exercise to the reader. For learning how they work, stat here.

Even though it's been written a thousand times, I felt like writing some JS.
var addCommas = function(number) {
number = '' + number;
var negative = false;
if (number.match(/^\-/)) {
negative = true;
}
number = number.replace(/[^0-9\.]/g, '');
number = number.split('.');
var before = number.shift()
, after = number.join('');
for (var i = (before.length - 3); i > 0; i -= 3) {
before = before.substr(0, i) + ',' + before.substr(i)
}
return (negative ? '-' : '') + before + (after ? '.' + after : '');
}
// 1,000.00
addCommas(1000.00);
// -1,234,567,890
addCommas('-1234567890');

Below is the approach to convert number format (comma separated)
HTML :-
<input type="text" onkeyup="convertNumberFormat(this.value)" />
JavaScript:-
function convertNumberFormat(inputValue)
{
inputValue = inputValue.toString();
inputValue = inputValue.replace( /\,/g, "");
var x = inputValue.split( '.' );
var intValue = x[0];
var floatValue = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while ( rgx.test(intValue) ) {
intValue = intValue.replace( rgx, '$1' + ',' + '$2' );
}
alert(intValue + floatValue);
}
In HTML template I am calling this function at "onkeyup" event.
you just need to call "convertNumberFormat" function whenever you want to validate your input value and pass current inserted value...
Example:-
convertNumberFormat('$2500');
Output:-
'$2,500' // in alert.
hope this can help you...

Related

Insert a Comma in the thousandths place in outputted number [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
I have created a function that takes a number in Imperial units entered into a div and converts that value to metric units in another div. Being relatively new to js, I am now realizing that a thousandths place comma separator does not come standard. I've tried to apply many of the solutions (many of them reg ex's) that I've found but none suit my needs or have worked. Simply put, I am just looking to have both divs outputted numbers have commas separating the thousandths place. Ultimately, these numbers are elevation values expressed in Feet and Meters. Any insight would be greatly appreciated... thanks!
Here is my code:
<body>
<div id="feet" onload="calculateMeter()">2120</div>
<div id="meter"></div>
<script>
var feet = document.getElementById('feet');
var meter = document.getElementById('meter');
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = (feet.innerHTML * 0.3048).toFixed(1);
feet.toString();
feet = feet.innerHTML.replace(/(\d)(\d{3})\,/, "$1,$2.");
}
}
calculateMeter();
</script>
</body>
Here is a simple RegEx solution
function calculateMeter() {
if (feet.innerHTML > 0) {
var m = (feet.innerHTML * 0.3048).toFixed(2);
meter.innerHTML = m.replace(/\B(?=(\d\d\d)+\b)/g, ",");
}
}
It seems your problem is actually just setting the content the DOM element. Using the solution in How to print a number with commas as thousands separators in JavaScript for formatting numbers, all you need is:
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = numberWithCommas*(feet.innerHTML * 0.3048).toFixed(1));
feet.innerHTML = numberWithCommas(feet.innerHTML);
}
}
My function:
function formatNumberWithCommasDec(d) {
d += "";
var c = d.split(".");
var f = c[1];
var a = c.length > 1 ? c[0] + '.' : '.', flag = false;
var g = f.split('').reverse(), y = 1, s = '';
for (var i = g.length - 1; i >= 0; i--) {
flag = false;
var e = g[i];
var h = (y === 3) ? s = s + e + ',' : s = s + e;
console.log(e);
if(y === 3){
y = 1;
flag = true;
} else {
y = y + 1;
}
}
if(flag){
s = s.substring(0, s.length - 1);
} else {
s = s;
}
return a + s;
}
Fiddle: https://jsfiddle.net/6f0tL0ec/1/
Update: found some problems, but everythings good now

Re-write malformed dates yyyy-M-d to yyyy-MM-dd in javascript using RegEx

So I'm rewriting dates in javacript and as familiar js spits dates like 2013-1-1 that isn't very useful always. Instead I'm looking for a routine that will form this date to the correct iso-version 2013-01-01
Today I make this by using string
var b = new Date('2013-1-1');
var result = b.getFullYear() + "-" +
(b.getMonth().toString().length == 1 ? "0" + parseInt(b.getMonth() + 1) : parseInt(b.getMonth() + 1)) + "-" +
(b.getDate().toString().length == 1 ? "0" + b.getDate() : b.getDate());
This works but it is ugly. Is there a better way to perform this using RegEx?
Please spare me of any anti-regex comments
A non-regex solution would be a generic padding function. First get your date in the non-padded version then you can split on the separator and pad it as necessary. Something like this:
var date = '2013-1-1';
var pad = function(n) {
return function(str) {
while (str.length < n) {
str = '0'+ str;
}
return str;
}
};
date = date.split(/-/g).map(pad(2)).join('-'); //=> 2013-01-01
may be this could help:
var str="2013-1-1";
var m = str.match(/^(\d{4})-(\d{1})-(\d{1})$/);
console.log([m[1], "0".concat([2]-1), "0".concat(m[3])].join('-'));
based on elclanrs suggestion I wrote an extension method
// Add 0 to single numbers
Number.prototype.padDate = function () {
// Add +1 if input is 0 (js months starts at 0)
var number = this == 0 ? 1 : this;
return number.toString().length == 1 ? "0" + number : number;
};
This allows me to build dates like this
var b = new Date('2013-1-1');
var result = b.getFullYear() + "-" + b.getMonth().padDate() + "-" + b.getDate().padDate();
Much cleaner, thanks

Adding comma as thousands separator (javascript) - output being deleted instead

I am attempting to dynamically adjust a numerical value entered to include thousand separators
Here is my code:
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
<input type="number" onkeyup="this.value=addCommas(this.value);" />
However when I enter numbers after the 4 one, the field is cleared.
Any ideas where I am going wrong? If there is a jQuery solution I'm already using that on my site.
Try this regex:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
To add the thousands separator you could string split, reverse, and replace calls like this:
function addThousandsSeparator(input) {
var output = input
if (parseFloat(input)) {
input = new String(input); // so you can perform string operations
var parts = input.split("."); // remove the decimal part
parts[0] = parts[0].split("").reverse().join("").replace(/(\d{3})(?!$)/g, "$1,").split("").reverse().join("");
output = parts.join(".");
}
return output;
}
addThousandsSeparator("1234567890"); // returns 1,234,567,890
addThousandsSeparator("12345678.90"); // returns 12,345,678.90
Try
<input type="text" onkeyup="this.value=addCommas(this.value);" />
instead. Since the function is working with text not numbers.
as Dillon mentioned, it needs to be a string (or you could use typeof(n) and stringify if not)
function addCommas(n){
var s=n.split('.')[1];
(s) ? s="."+s : s="";
n=n.split('.')[0]
while(n.length>3){
s=","+n.substr(n.length-3,3)+s;
n=n.substr(0,n.length-3)
}
return n+s
}
In each case before formatting try to remove existing commas first, like there: Removing commas in 'live' input fields in jquery
Example:
function addThousandsSeparator(x) {
//remove commas
retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;
//apply formatting
return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

How can I add a comma to separate each group of three digits in a text input field?

I have a text input field for a form where users are meant to enter a number. I would like to automatically insert a comma after every third digit.
For example, entering '20' would result in '20'. Entering '100' would result in '100'. But if they were to enter '1000', a comma would be inserted between the 1 and the following 0's (e.g., 1,000). Obviously this behaviour would continue should the number reach 7 digits (e.g., 1,000,000).
Is there an easy way to do this? I'm a bit of a newb at all of this, so please answer like you're talking to a child :)
The following javascript:
function format(input)
{
var nStr = input.value + '';
nStr = nStr.replace( /\,/g, "");
var x = nStr.split( '.' );
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while ( rgx.test(x1) ) {
x1 = x1.replace( rgx, '$1' + ',' + '$2' );
}
input.value = x1 + x2;
}
and the following HTML:
<input type="text" onkeyup="format(this)">
should solve your problem. The key is to use 'onkeyup'.
Try it here http://jsfiddle.net/YUSph/
for the fun of it:
'9876543210'
.split('') // flip the entire string so that we can break every
.reverse() // 3rd digit, starting from the end
.join('')
.split(/(...)/) // split on every 3rd
.reverse() // flip the string again, though now each group of 3 is
.join(',') // backwards
.replace(/,(?=,)|,$|^,/g, '') // remove extra ,
.replace(/(,|^)(\d)(\d)?(\d)?/g, '$1$4$3$2') // flip each group of digits
// 9,876,543,210
Anyone want to take a stab at making that better?
function addCommas(nStr){
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Pass the value of the input into function and set the input with the result returned. You can bind this to an onchange event.
Here is a working example that relies on jquery to bind the change event and set the value: http://jsfiddle.net/TYyfn/
Comma script is from: http://www.mredkj.com/javascript/nfbasic.html
Yes, it's not terribly difficult. I believe this reference may give you what you need.
Note that for this to be dynamic (as they type) you'd need to have this wired to the input field change handler. Otherwise, you can wire this to the input field blur handler (which will have the effect of putting the commas in the field when they leave the field).
Give this a try: it may need a little tweeking.
take the function from above: function addCommas(nStr){...} and put in a js file.
add a script link in the page header to jquery library with:
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
be sure your text box has a unique id. ex: id="comma_input".
in the same js file add
$(document).ready(function(){
$('#comma_input').keyup(function(){
$(this).attr('value',addCommas($(this).attr('value')));
});
});
function addCommas(nStr){
var offset = nStr.length % 3;
if (offset == 0)
return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,");
else
return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})/g, ",$1");
}
alert(addCommas("1234567"));
Another way to do it, no RegEx, just array manipulation:
function decimalMark(s) {
for (var a = s.split("").reverse(), b = [], i = 0; i < a.length; i++) {
if (i && i%3 === 0)
b.unshift(",");
b.unshift(a[i]);
}
return b.join("");
}
Be sure to pass a string to the function
decimalMark("1234")
Simple string solution in pure JS:
function addCommas(e) {
var tgt = e.target, val = tgt.value.replace(/,/g, ''),
amt = Math.ceil(val.length/3), newStr = '', x = 0;
while ( x <= amt ) {
newStr += val.slice(x*3,(x+1)*3);
newStr += ( x < amt-1 ) ? ',' : '';
x++
}
tgt.value = newStr;
}
document.getElementById('test').addEventListener('change', addCommas, false);
Demo: http://jsfiddle.net/kevinvanlierde/TYyfn/141/
You can use standart JavaScript functions. Example here;
http://jsfiddle.net/azur/jD5pa/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>pure js solution</title>
<script type='text/javascript'>
function digitGroup(dInput) {
var output = "";
try {
dInput = dInput.replace(/[^0-9]/g, ""); // remove all chars including spaces, except digits.
var totalSize = dInput.length;
for (var i = totalSize - 1; i > -1; i--) {
output = dInput.charAt(i) + output;
var cnt = totalSize - i;
if (cnt % 3 === 0 && i !== 0) {
output = " " + output; // seperator is " "
}
}
} catch (err)
{
output = dInput; // it won't happen, but it's sweet to catch exceptions.
}
return output;
}
</script>
</head>
<body>
<input type="text" value="53" onkeyup="this.value = digitGroup(this.value);">
</body>
</html>
var formatNumber = function(num, type) {
var numSplit, int, dec, type;
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.')
int = numSplit[0];
if (int.length >= 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3);
}
dec = numSplit[1];
return (type === 'exp'? sign = '-' : '+') + ' ' + int + '.' + dec;
};

add commas to a number in jQuery

I have these numbers
10999 and 8094 and 456
And all i want to do is add a comma in the right place if it needs it so it looks like this
10,999 and 8,094 and 456
These are all within a p tag like this <p class="points">10999</p> etc.
Can it be done?
I've attempted it here with the help of other posts http://jsfiddle.net/pdWTU/1/ but can't seem to get it to work
Thanks
Jamie
UPDATE
Messed around a bit and managed to figure it out here http://jsfiddle.net/W5jwY/1/
Going to look at the new Globalization plugin for a better way of doing it
Thanks
Jamie
Works on all browsers, this is all you need.
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:
$('#elementID').html(commaSeparateNumber(1234567890));
or
$('#inputID').val(commaSeparateNumber(1234567890));
However, if you require something cleaner, with flexibility. The below code will fix decimals correctly, remove leading zeros, and can be used limitlessly. Thanks to #baacke in the comments.
function commaSeparateNumber(val){
val = val.toString().replace(/,/g, ''); //remove existing commas first
var valRZ = val.replace(/^0+/, ''); //remove leading zeros, optional
var valSplit = valRZ.split('.'); //then separate decimals
while (/(\d+)(\d{3})/.test(valSplit[0].toString())){
valSplit[0] = valSplit[0].toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
if(valSplit.length == 2){ //if there were decimals
val = valSplit[0] + "." + valSplit[1]; //add decimals back
}else{
val = valSplit[0]; }
return val;
}
And in your jQuery, use like so:
$('.your-element').each(function(){
$(this).html(commaSeparateNumber($(this).html()));
});
Here's the jsFiddle.
Number(10000).toLocaleString('en'); // "10,000"
Timothy Pirez answer was very correct but if you need to replace the numbers with commas Immediately as user types in textfield, u might want to use the Keyup function.
$('#textfield').live('keyup', function (event) {
var value=$('#textfield').val();
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var newvalue=value.replace(/,/g, '');
var valuewithcomma=Number(newvalue).toLocaleString('en');
$('#textfield').val(valuewithcomma);
});
<form><input type="text" id="textfield" ></form>
Take a look at recently released Globalization plugin to jQuery by Microsoft
Take a look at Numeral.js. It can format numbers, currency, percentages and has support for localization.
function delimitNumbers(str) {
return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
});
}
alert(delimitNumbers(1234567890));
I'm guessing that you're doing some sort of localization, so have a look at this script.
Using toLocaleString
ref at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
function formatComma(value, sep = 0) {
return Number(value).toLocaleString("ja-JP", { style: "currency", currency: "JPY", minimumFractionDigits: sep });
}
console.log(formatComma(123456789, 2)); // ¥123,456,789.00
console.log(formatComma(123456789, 0)); // ¥123,456,789
console.log(formatComma(1234, 0)); // ¥1,234
another approach:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
var a = addCommas(10000.00);
alert(a);
Another amazing plugin:
http://www.teamdf.com/web/jquery-number-format/178/
Another way to do it:
function addCommas(n){
var s = "",
r;
while (n) {
r = n % 1000;
s = r + s;
n = (n - r)/1000;
s = (n ? "," : "") + s;
}
return s;
}
alert(addCommas(12345678));
Here is my coffeescript version of #baacke's fiddle provided in a comment to #Timothy Perez
class Helpers
#intComma: (number) ->
# remove any existing commas
comma = /,/g
val = number.toString().replace comma, ''
# separate the decimals
valSplit = val.split '.'
integer = valSplit[0].toString()
expression = /(\d+)(\d{3})/
while expression.test(integer)
withComma = "$1,$2"
integer = integer.toString().replace expression, withComma
# recombine with decimals if any
val = integer
if valSplit.length == 2
val = "#{val}.#{valSplit[1]}"
return val

Categories