i have here a sample computation, what i want to know is how can it be a money format output.
for example 1000+ 1000 =2000
i want to output it as 2,000.
also , when typing the value , i want it automatically look a money format.
<html>
<head>
</head>
<body>
<form name="haha" method="post" >
1:<input type="text" name="num1">
2:<input type="text" name="num2">
Total:<input type="label" name="total">
<input type="submit" value="add" name="submit">
</html>
</form>
<?
if (isset($_POST['submit']))
{
$num1=$_POST['num1'];
$num2=$_POST['num2'];
$total=$_POST['total'];
$total= $num1 + $num2;
echo $total;
}
?>
Try number_format
$english_format_number = number_format(floatval($total));
echo $english_format_number;
I'm assuming you're looking for number_format or its more advanced brother money_format. This will take care of the server-side for you.
As for the client-side, I would advise against making things change while the user's typing. Just let them type in the number how they want. Bonus points if you allow them to type in thousand separators (since you can just strip them out easily in PHP to get the number itself).
You need to use javascript for that, when user change the input value you need to call the function to format the value.
You have to something like this:
$("[name^='num']").change(function(){
var value = $(this).val();
$(this).val(money_format(format, value));
});
Here is the function for monet format :
Ref: https://github.com/kvz/phpjs/blob/master/functions/strings/money_format.js
function money_format (format, number) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brett-zamir.me)
// + input by: daniel airton wermann (http://wermann.com.br)
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// - depends on: setlocale
// % note 1: This depends on setlocale having the appropriate locale (these examples use 'en_US')
// * example 1: money_format('%i', 1234.56);
// * returns 1: 'USD 1,234.56'
// * example 2: money_format('%14#8.2n', 1234.5678);
// * returns 2: ' $ 1,234.57'
// * example 3: money_format('%14#8.2n', -1234.5678);
// * returns 3: '-$ 1,234.57'
// * example 4: money_format('%(14#8.2n', 1234.5678);
// * returns 4: ' $ 1,234.57 '
// * example 5: money_format('%(14#8.2n', -1234.5678);
// * returns 5: '($ 1,234.57)'
// * example 6: money_format('%=014#8.2n', 1234.5678);
// * returns 6: ' $000001,234.57'
// * example 7: money_format('%=014#8.2n', -1234.5678);
// * returns 7: '-$000001,234.57'
// * example 8: money_format('%=*14#8.2n', 1234.5678);
// * returns 8: ' $*****1,234.57'
// * example 9: money_format('%=*14#8.2n', -1234.5678);
// * returns 9: '-$*****1,234.57'
// * example 10: money_format('%=*^14#8.2n', 1234.5678);
// * returns 10: ' $****1234.57'
// * example 11: money_format('%=*^14#8.2n', -1234.5678);
// * returns 11: ' -$****1234.57'
// * example 12: money_format('%=*!14#8.2n', 1234.5678);
// * returns 12: ' *****1,234.57'
// * example 13: money_format('%=*!14#8.2n', -1234.5678);
// * returns 13: '-*****1,234.57'
// * example 14: money_format('%i', 3590);
// * returns 14: ' USD 3,590.00'
// Per PHP behavior, there seems to be no extra padding for sign when there is a positive number, though my
// understanding of the description is that there should be padding; need to revisit examples
// Helpful info at http://ftp.gnu.org/pub/pub/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_7.html and http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/strfmp.htm
if (typeof number !== 'number') {
return null;
}
var regex = /%((=.|[+^(!-])*?)(\d*?)(#(\d+))?(\.(\d+))?([in%])/g; // 1: flags, 3: width, 5: left, 7: right, 8: conversion
this.setlocale('LC_ALL', 0); // Ensure the locale data we need is set up
var monetary = this.php_js.locales[this.php_js.localeCategories['LC_MONETARY']]['LC_MONETARY'];
var doReplace = function (n0, flags, n2, width, n4, left, n6, right, conversion) {
var value = '',
repl = '';
if (conversion === '%') { // Percent does not seem to be allowed with intervening content
return '%';
}
var fill = flags && (/=./).test(flags) ? flags.match(/=(.)/)[1] : ' '; // flag: =f (numeric fill)
var showCurrSymbol = !flags || flags.indexOf('!') === -1; // flag: ! (suppress currency symbol)
width = parseInt(width, 10) || 0; // field width: w (minimum field width)
var neg = number < 0;
number = number + ''; // Convert to string
number = neg ? number.slice(1) : number; // We don't want negative symbol represented here yet
var decpos = number.indexOf('.');
var integer = decpos !== -1 ? number.slice(0, decpos) : number; // Get integer portion
var fraction = decpos !== -1 ? number.slice(decpos + 1) : ''; // Get decimal portion
var _str_splice = function (integerStr, idx, thous_sep) {
var integerArr = integerStr.split('');
integerArr.splice(idx, 0, thous_sep);
return integerArr.join('');
};
var init_lgth = integer.length;
left = parseInt(left, 10);
var filler = init_lgth < left;
if (filler) {
var fillnum = left - init_lgth;
integer = new Array(fillnum + 1).join(fill) + integer;
}
if (flags.indexOf('^') === -1) { // flag: ^ (disable grouping characters (of locale))
// use grouping characters
var thous_sep = monetary.mon_thousands_sep; // ','
var mon_grouping = monetary.mon_grouping; // [3] (every 3 digits in U.S.A. locale)
if (mon_grouping[0] < integer.length) {
for (var i = 0, idx = integer.length; i < mon_grouping.length; i++) {
idx -= mon_grouping[i]; // e.g., 3
if (idx <= 0) {
break;
}
if (filler && idx < fillnum) {
thous_sep = fill;
}
integer = _str_splice(integer, idx, thous_sep);
}
}
if (mon_grouping[i - 1] > 0) { // Repeating last grouping (may only be one) until highest portion of integer reached
while (idx > mon_grouping[i - 1]) {
idx -= mon_grouping[i - 1];
if (filler && idx < fillnum) {
thous_sep = fill;
}
integer = _str_splice(integer, idx, thous_sep);
}
}
}
// left, right
if (right === '0') { // No decimal or fractional digits
value = integer;
} else {
var dec_pt = monetary.mon_decimal_point; // '.'
if (right === '' || right === undefined) {
right = conversion === 'i' ? monetary.int_frac_digits : monetary.frac_digits;
}
right = parseInt(right, 10);
if (right === 0) { // Only remove fractional portion if explicitly set to zero digits
fraction = '';
dec_pt = '';
} else if (right < fraction.length) {
fraction = Math.round(parseFloat(fraction.slice(0, right) + '.' + fraction.substr(right, 1))) + '';
if (right > fraction.length) {
fraction = new Array(right - fraction.length + 1).join('0') + fraction; // prepend with 0's
}
} else if (right > fraction.length) {
fraction += new Array(right - fraction.length + 1).join('0'); // pad with 0's
}
value = integer + dec_pt + fraction;
}
var symbol = '';
if (showCurrSymbol) {
symbol = conversion === 'i' ? monetary.int_curr_symbol : monetary.currency_symbol; // 'i' vs. 'n' ('USD' vs. '$')
}
var sign_posn = neg ? monetary.n_sign_posn : monetary.p_sign_posn;
// 0: no space between curr. symbol and value
// 1: space sep. them unless symb. and sign are adjacent then space sep. them from value
// 2: space sep. sign and value unless symb. and sign are adjacent then space separates
var sep_by_space = neg ? monetary.n_sep_by_space : monetary.p_sep_by_space;
// p_cs_precedes, n_cs_precedes // positive currency symbol follows value = 0; precedes value = 1
var cs_precedes = neg ? monetary.n_cs_precedes : monetary.p_cs_precedes;
// Assemble symbol/value/sign and possible space as appropriate
if (flags.indexOf('(') !== -1) { // flag: parenth. for negative
// Fix: unclear on whether and how sep_by_space, sign_posn, or cs_precedes have
// an impact here (as they do below), but assuming for now behaves as sign_posn 0 as
// far as localized sep_by_space and sign_posn behavior
repl = (cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') : '') + value + (!cs_precedes ? (sep_by_space === 1 ? ' ' : '') + symbol : '');
if (neg) {
repl = '(' + repl + ')';
} else {
repl = ' ' + repl + ' ';
}
} else { // '+' is default
var pos_sign = monetary.positive_sign; // ''
var neg_sign = monetary.negative_sign; // '-'
var sign = neg ? (neg_sign) : (pos_sign);
var otherSign = neg ? (pos_sign) : (neg_sign);
var signPadding = '';
if (sign_posn) { // has a sign
signPadding = new Array(otherSign.length - sign.length + 1).join(' ');
}
var valueAndCS = '';
switch (sign_posn) {
// 0: parentheses surround value and curr. symbol;
// 1: sign precedes them;
// 2: sign follows them;
// 3: sign immed. precedes curr. symbol; (but may be space between)
// 4: sign immed. succeeds curr. symbol; (but may be space between)
case 0:
valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol;
repl = '(' + valueAndCS + ')';
break;
case 1:
valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol;
repl = signPadding + sign + (sep_by_space === 2 ? ' ' : '') + valueAndCS;
break;
case 2:
valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol;
repl = valueAndCS + (sep_by_space === 2 ? ' ' : '') + sign + signPadding;
break;
case 3:
repl = cs_precedes ? signPadding + sign + (sep_by_space === 2 ? ' ' : '') + symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + sign + signPadding + (sep_by_space === 2 ? ' ' : '') + symbol;
break;
case 4:
repl = cs_precedes ? symbol + (sep_by_space === 2 ? ' ' : '') + signPadding + sign + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol + (sep_by_space === 2 ? ' ' : '') + sign + signPadding;
break;
}
}
var padding = width - repl.length;
if (padding > 0) {
padding = new Array(padding + 1).join(' ');
// Fix: How does p_sep_by_space affect the count if there is a space? Included in count presumably?
if (flags.indexOf('-') !== -1) { // left-justified (pad to right)
repl += padding;
} else { // right-justified (pad to left)
repl = padding + repl;
}
}
return repl;
};
return format.replace(regex, doReplace);
}
Related
JQuery turns the form input field :
<form method="post" action="./action.php">
<input type="text" class="timepicker" name="timepicker" id="timepicker" />
.
.
</form>
into
JQuery :
/* jQuery timepicker
* replaces a single text input with a set of pulldowns to select hour, minute, and am/pm
*
* Copyright (c) 2007 Jason Huck/Core Five Creative (http://www.corefive.com/)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version 1.0
*/
(function($){
jQuery.fn.timepicker = function(){
this.each(function(){
// get the ID and value of the current element
var i = this.id;
var v = $(this).val();
// the options we need to generate
var hrs = new Array('01','02','03','04','05','06','07','08','09','10','11','12');
var mins = new Array('00','15','30','45');
var ap = new Array('am','pm');
// default to the current time
var d = new Date;
var h = d.getHours();
var m = d.getMinutes();
var p = (h >= 12 ? 'pm' : 'am');
// adjust hour to 12-hour format
if(h > 12) h = h - 12;
// round minutes to nearest quarter hour
for(mn in mins){
if(m <= parseInt(mins[mn])){
m = parseInt(mins[mn]);
break;
}
}
// increment hour if we push minutes to next 00
if(m > 45){
m = 0;
switch(h){
case(11):
h += 1;
p = (p == 'am' ? 'pm' : 'am');
break;
case(12):
h = 1;
break;
default:
h += 1;
break;
}
}
// override with current values if applicable
if(v.length == 7){
h = parseInt(v.substr(0,2));
m = parseInt(v.substr(3,2));
p = v.substr(5);
}
// build the new DOM objects
var output = '';
output += '<select id="h_' + i + '" class="h timepicker">';
for(hr in hrs){
output += '<option value="' + hrs[hr] + '"';
if(parseInt(hrs[hr]) == h) output += ' selected';
output += '>' + hrs[hr] + '</option>';
}
output += '</select>';
output += '<select id="m_' + i + '" class="m timepicker">';
for(mn in mins){
output += '<option value="' + mins[mn] + '"';
if(parseInt(mins[mn]) == m) output += ' selected';
output += '>' + mins[mn] + '</option>';
}
output += '</select>';
output += '<select id="p_' + i + '" class="p timepicker">';
for(pp in ap){
output += '<option value="' + ap[pp] + '"';
if(ap[pp] == p) output += ' selected';
output += '>' + ap[pp] + '</option>';
}
output += '</select>';
// hide original input and append new replacement inputs
$(this).attr('type','hidden').after(output);
});
$('select.timepicker').change(function(){
var i = this.id.substr(2);
var h = $('#h_' + i).val();
var m = $('#m_' + i).val();
var p = $('#p_' + i).val();
var v = h + ':' + m + p;
$('#' + i).val(v);
});
return this;
};
})(jQuery);
$(document).ready(function() {
$('.timepicker').timepicker();
});
/* SVN: $Id: jquery.timepicker.js 456 2007-07-16 19:09:57Z Jason Huck $ */
On form submit, as I try to get the default value of the field using $_POST['timepicker'] , I get a blank.
Why is that ? How can I get the default value from the field ?
The code dynamically creates some <select> elements for the hours and minutes but these do not have a name attribute so they are not submitted when the form is POSTed.
The value from these selects is saved into a hidden form field which has a name attribute (and so get's POSTed) - but this only happens when a value in the <select> elements is changed.
To allow the default to be submitted, you can manually trigger the "change" event in your "ready" function, like this:
$(document).ready(function() {
$('.timepicker').timepicker();
$('.timepicker').trigger('change');
});
I would like to compare to set of text and get how similar/relevant they are to each other, I use similar_text(), but i found out its not as accurate. Thank you.
For example the following text gives me 66%
Text1: Innovation game, eat, sleep, breathe innovation. It love creativity & passion power Internet drives . We understand time greatest asset, challege meet deadline.
Text2: Soviet union communist policy; Germany league organization disguise enermies beaten wanted.
My code is as below:
echo $student_answer = removeCommonWords($answer)."<br><br>";
$student_answer = strip_tags($student_answer);
echo $memo = removeCommonWords2($memo)."<br><br>";
echo similar_text($memo, $student_answer);
You can use the JS version:
http://phpjs.org/functions/similar_text/
The JS code shows you the precent code (you can modify the code):
return (sum * 200) / (firstLength + secondLength);
I hope this will help you!
EDIT:
How to use similar_text in JS?
Create a file named similar_text.js and copy&paste this code in it:
function similar_text (first, second, percent) {
// http://kevin.vanzonneveld.net
// + original by: Rafał Kukawski (http://blog.kukawski.pl)
// + bugfixed by: Chris McMacken
// + added percent parameter by: Markus Padourek (taken from http://www.kevinhq.com/2012/06/php-similartext-function-in-javascript_16.html)
// * example 1: similar_text('Hello World!', 'Hello phpjs!');
// * returns 1: 7
// * example 2: similar_text('Hello World!', null);
// * returns 2: 0
// * example 3: similar_text('Hello World!', null, 1);
// * returns 3: 58.33
if (first === null || second === null || typeof first === 'undefined' || typeof second === 'undefined') {
return 0;
}
first += '';
second += '';
var pos1 = 0,
pos2 = 0,
max = 0,
firstLength = first.length,
secondLength = second.length,
p, q, l, sum;
max = 0;
for (p = 0; p < firstLength; p++) {
for (q = 0; q < secondLength; q++) {
for (l = 0;
(p + l < firstLength) && (q + l < secondLength) && (first.charAt(p + l) === second.charAt(q + l)); l++);
if (l > max) {
max = l;
pos1 = p;
pos2 = q;
}
}
}
sum = max;
if (sum) {
if (pos1 && pos2) {
sum += this.similar_text(first.substr(0, pos2), second.substr(0, pos2));
}
if ((pos1 + max < firstLength) && (pos2 + max < secondLength)) {
sum += this.similar_text(first.substr(pos1 + max, firstLength - pos1 - max), second.substr(pos2 + max, secondLength - pos2 - max));
}
}
if (!percent) {
return sum;
} else {
return (sum * 200) / (firstLength + secondLength);
}
}
In your put the following line:
<script type="text/JavaScript" src="YOUR_PATH/similar_text.js"></script>
Now you can use it in your body:
<script>
similar_text('Hello World!', 'Hello phpjs!');
</script>
It will output 7.
Hope this wil help you!
I have a code not very professional but it does what i want :). The code is basically doing if shop open count for how long if closed count how long left form opening. Now i wanted to style it with jQuery Countdown but i cant find any to just count hours,minutes, maybe seconds. I was trying UNIX countdowns but dunno what i`m doing wrong. I would like to ask you fellow citizens of Stackoverflow to help me out with this.
This is my code ( Just don`t be haters :) )
date_default_timezone_set('Greenwich'); //Fixes my server location
$openingtime = strtotime('06:00'); //Opening time
$closingtime = strtotime('23:10'); //Closing time
$timenow = strtotime('now'); //Current Server Time
$twentyfourhours = "24:00"; //Hours in a day
//echo date('G:i', $openingtime); //Just texting
//echo date('G:i', $closingtime);
//echo date('H:i', $timenow);
//echo $twentyfourhours;// Testing ends here
$openingin = $twentyfourhours - $timenow + $openingtime; //24:00 - 23:20 + 6:00 = How long left for opening
$closingdown = $closingtime - $timenow; //23:10 - 23:20 How long left to close
//If current time value is bigger then closing time then display when the shop will re-open again
if (date('H:i', $timenow) > date('H:i', $closingtime))
{
echo "The shop will be open in ".date('H:i', $openingin)." hours";
}
//If current time value is lower then closing time then display how long the shop will stay open
elseif (date('H:i', $timenow) < date('H:i', $closingtime))
{
echo "The shop will be open for ".date('H:i', $closingdown)." hours";
}
Ok i have managed to found one but now if you will go to My Testing Ground You will notice that the seconds instead of starting countdown from 60 they start from 00,99,98,97,97 and all the way down :( dunno why its happening im attaching JS code
var flipCounter = function(d, options){
// Default values
var defaults = {
value: 0,
inc: 1,
pace: 1000,
auto: true,
tFH: 39,
bFH: 64,
fW: 53,
bOffset: 390
};
var o = options || {},
doc = window.document,
divId = typeof d !== 'undefined' && d !== '' ? d : 'flip-counter',
div = doc.getElementById(divId);
for (var opt in defaults) o[opt] = (opt in o) ? o[opt] : defaults[opt];
var digitsOld = [], digitsNew = [], subStart, subEnd, x, y, nextCount = null, newDigit, newComma,
best = {
q: null,
pace: 0,
inc: 0
};
/**
* Sets the value of the counter and animates the digits to new value.
*
* Example: myCounter.setValue(500); would set the value of the counter to 500,
* no matter what value it was previously.
*
* #param {int} n
* New counter value
*/
this.setValue = function(n){
if (isNumber(n)){
x = o.value;
y = n;
o.value = n;
digitCheck(x,y);
}
return this;
};
/**
* Sets the increment for the counter. Does NOT animate digits.
*/
this.setIncrement = function(n){
o.inc = isNumber(n) ? n : defaults.inc;
return this;
};
/**
* Sets the pace of the counter. Only affects counter when auto == true.
*
* #param {int} n
* New pace for counter in milliseconds
*/
this.setPace = function(n){
o.pace = isNumber(n) ? n : defaults.pace;
return this;
};
/**
* Sets counter to auto-incrememnt (true) or not (false).
*
* #param {bool} a
* Should counter auto-increment, true or false
*/
this.setAuto = function(a){
if (a && ! o.atuo){
o.auto = true;
doCount();
}
if (! a && o.auto){
if (nextCount) clearNext();
o.auto = false;
}
return this;
};
/**
* Increments counter by one animation based on set 'inc' value.
*/
this.step = function(){
if (! o.auto) doCount();
return this;
};
/**
* Adds a number to the counter value, not affecting the 'inc' or 'pace' of the counter.
*
* #param {int} n
* Number to add to counter value
*/
this.add = function(n){
if (isNumber(n)){
x = o.value;
o.value += n;
y = o.value;
digitCheck(x,y);
}
return this;
};
/**
* Subtracts a number from the counter value, not affecting the 'inc' or 'pace' of the counter.
*
* #param {int} n
* Number to subtract from counter value
*/
this.subtract = function(n){
if (isNumber(n)){
x = o.value;
o.value -= n;
if (o.value >= 0){
y = o.value;
}
else{
y = "0";
o.value = 0;
}
digitCheck(x,y);
}
return this;
};
/**
* Increments counter to given value, animating by current pace and increment.
*
* #param {int} n
* Number to increment to
* #param {int} t (optional)
* Time duration in seconds - makes increment a 'smart' increment
* #param {int} p (optional)
* Desired pace for counter if 'smart' increment
*/
this.incrementTo = function(n, t, p){
if (nextCount) clearNext();
// Smart increment
if (typeof t != 'undefined'){
var time = isNumber(t) ? t * 1000 : 10000,
pace = typeof p != 'undefined' && isNumber(p) ? p : o.pace,
diff = typeof n != 'undefined' && isNumber(n) ? n - o.value : 0,
cycles, inc, check, i = 0;
best.q = null;
// Initial best guess
pace = (time / diff > pace) ? Math.round((time / diff) / 10) * 10 : pace;
cycles = Math.floor(time / pace);
inc = Math.floor(diff / cycles);
check = checkSmartValues(diff, cycles, inc, pace, time);
if (diff > 0){
while (check.result === false && i < 100){
pace += 10;
cycles = Math.floor(time / pace);
inc = Math.floor(diff / cycles);
check = checkSmartValues(diff, cycles, inc, pace, time);
i++;
}
if (i == 100){
// Could not find optimal settings, use best found so far
o.inc = best.inc;
o.pace = best.pace;
}
else{
// Optimal settings found, use those
o.inc = inc;
o.pace = pace;
}
doIncrement(n, true, cycles);
}
}
// Regular increment
else{
doIncrement(n);
}
}
/**
* Gets current value of counter.
*/
this.getValue = function(){
return o.value;
}
/**
* Stops all running increments.
*/
this.stop = function(){
if (nextCount) clearNext();
return this;
}
//---------------------------------------------------------------------------//
function doCount(){
x = o.value;
o.value += o.inc;
y = o.value;
digitCheck(x,y);
if (o.auto === true) nextCount = setTimeout(doCount, o.pace);
}
function doIncrement(n, s, c){
var val = o.value,
smart = (typeof s == 'undefined') ? false : s,
cycles = (typeof c == 'undefined') ? 1 : c;
if (smart === true) cycles--;
if (val != n){
x = o.value,
o.auto = true;
if (val + o.inc <= n && cycles != 0) val += o.inc
else val = n;
o.value = val;
y = o.value;
digitCheck(x,y);
nextCount = setTimeout(function(){doIncrement(n, smart, cycles)}, o.pace);
}
else o.auto = false;
}
function digitCheck(x,y){
digitsOld = splitToArray(x);
digitsNew = splitToArray(y);
var diff,
xlen = digitsOld.length,
ylen = digitsNew.length;
if (ylen > xlen){
diff = ylen - xlen;
while (diff > 0){
addDigit(ylen - diff + 1, digitsNew[ylen - diff]);
diff--;
}
}
if (ylen < xlen){
diff = xlen - ylen;
while (diff > 0){
removeDigit(xlen - diff);
diff--;
}
}
for (var i = 0; i < xlen; i++){
if (digitsNew[i] != digitsOld[i]){
animateDigit(i, digitsOld[i], digitsNew[i]);
}
}
}
function animateDigit(n, oldDigit, newDigit){
var speed, step = 0, w, a,
bp = [
'-' + o.fW + 'px -' + (oldDigit * o.tFH) + 'px',
(o.fW * -2) + 'px -' + (oldDigit * o.tFH) + 'px',
'0 -' + (newDigit * o.tFH) + 'px',
'-' + o.fW + 'px -' + (oldDigit * o.bFH + o.bOffset) + 'px',
(o.fW * -2) + 'px -' + (newDigit * o.bFH + o.bOffset) + 'px',
(o.fW * -3) + 'px -' + (newDigit * o.bFH + o.bOffset) + 'px',
'0 -' + (newDigit * o.bFH + o.bOffset) + 'px'
];
if (o.auto === true && o.pace <= 300){
switch (n){
case 0:
speed = o.pace/6;
break;
case 1:
speed = o.pace/5;
break;
case 2:
speed = o.pace/4;
break;
case 3:
speed = o.pace/3;
break;
default:
speed = o.pace/1.5;
break;
}
}
else{
speed = 80;
}
// Cap on slowest animation can go
speed = (speed > 80) ? 80 : speed;
function animate(){
if (step < 7){
w = step < 3 ? 't' : 'b';
a = doc.getElementById(divId + "_" + w + "_d" + n);
if (a) a.style.backgroundPosition = bp[step];
step++;
if (step != 3) setTimeout(animate, speed);
else animate();
}
}
animate();
}
// Creates array of digits for easier manipulation
function splitToArray(input){
return input.toString().split("").reverse();
}
// Adds new digit
function addDigit(len, digit){
var li = Number(len) - 1;
newDigit = doc.createElement("ul");
newDigit.className = 'cd';
newDigit.id = divId + '_d' + li;
newDigit.innerHTML = '<li class="t" id="' + divId + '_t_d' + li + '"></li><li class="b" id="' + divId + '_b_d' + li + '"></li>';
if (li % 2 == 0){
newComma = doc.createElement("ul");
newComma.className = 'cd';
newComma.innerHTML = '<li class="s"></li>';
div.insertBefore(newComma, div.firstChild);
}
div.insertBefore(newDigit, div.firstChild);
doc.getElementById(divId + "_t_d" + li).style.backgroundPosition = '0 -' + (digit * o.tFH) + 'px';
doc.getElementById(divId + "_b_d" + li).style.backgroundPosition = '0 -' + (digit * o.bFH + o.bOffset) + 'px';
}
// Removes digit
function removeDigit(id){
var remove = doc.getElementById(divId + "_d" + id);
div.removeChild(remove);
// Check for leading comma
var first = div.firstChild.firstChild;
if ((" " + first.className + " ").indexOf(" s ") > -1 ){
remove = first.parentNode;
div.removeChild(remove);
}
}
// Sets the correct digits on load
function initialDigitCheck(init){
// Creates the right number of digits
var initial = init.toString(),
count = initial.length,
bit = 1, i;
for (i = 0; i < count; i++){
newDigit = doc.createElement("ul");
newDigit.className = 'cd';
newDigit.id = divId + '_d' + i;
newDigit.innerHTML = newDigit.innerHTML = '<li class="t" id="' + divId + '_t_d' + i + '"></li><li class="b" id="' + divId + '_b_d' + i + '"></li>';
div.insertBefore(newDigit, div.firstChild);
if (bit != (count) && bit % 2 == 0){
newComma = doc.createElement("ul");
newComma.className = 'cd';
newComma.innerHTML = '<li class="s"></li>';
div.insertBefore(newComma, div.firstChild);
}
bit++;
}
// Sets them to the right number
var digits = splitToArray(initial);
for (i = 0; i < count; i++){
doc.getElementById(divId + "_t_d" + i).style.backgroundPosition = '0 -' + (digits[i] * o.tFH) + 'px';
doc.getElementById(divId + "_b_d" + i).style.backgroundPosition = '0 -' + (digits[i] * o.bFH + o.bOffset) + 'px';
}
// Do first animation
if (o.auto === true) nextCount = setTimeout(doCount, o.pace);
}
// Checks values for smart increment and creates debug text
function checkSmartValues(diff, cycles, inc, pace, time){
var r = {result: true}, q;
// Test conditions, all must pass to continue:
// 1: Unrounded inc value needs to be at least 1
r.cond1 = (diff / cycles >= 1) ? true : false;
// 2: Don't want to overshoot the target number
r.cond2 = (cycles * inc <= diff) ? true : false;
// 3: Want to be within 10 of the target number
r.cond3 = (Math.abs(cycles * inc - diff) <= 10) ? true : false;
// 4: Total time should be within 100ms of target time.
r.cond4 = (Math.abs(cycles * pace - time) <= 100) ? true : false;
// 5: Calculated time should not be over target time
r.cond5 = (cycles * pace <= time) ? true : false;
// Keep track of 'good enough' values in case can't find best one within 100 loops
if (r.cond1 && r.cond2 && r.cond4 && r.cond5){
q = Math.abs(diff - (cycles * inc)) + Math.abs(cycles * pace - time);
if (best.q === null) best.q = q;
if (q <= best.q){
best.pace = pace;
best.inc = inc;
}
}
for (var i = 1; i <= 5; i++){
if (r['cond' + i] === false){
r.result = false;
}
}
return r;
}
// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/1830844
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function clearNext(){
clearTimeout(nextCount);
nextCount = null;
}
// Start it up
initialDigitCheck(o.value);
};`
PHP Function:
function formatNumberForDisplay($number, $decimal=0, $decimalSeperator='.', $numberSeperator=',')
{
return number_format($number, $decimal, $decimalSeperator, $numberSeperator);
}
Can anybody suggest to me the equivalent functionality in jQuery/JavaScript?
The same equivalent of number_format in js can found here
function number_format (number, decimals, dec_point, thousands_sep) {
// Strip all characters but numerical ones.
number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
Just use toLocaleString on an integer object.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_compatibility
let x = 1234567;
//if x is a string/non-number, use parseInt/parseFloat to convert to a number. Thanks #Aleksandr Kopelevich
x.toLocaleString('us', {minimumFractionDigits: 2, maximumFractionDigits: 2})
is this what you'd like to get?
yourFloatVarHere.toFixed(2);
voilà.
Native "Intl" object approach:
var amount = 5000.25;
var locale = 'de';
var options = {style: 'currency', currency: 'eur', minimumFractionDigits: 2, maximumFractionDigits: 2};
var formatter = new Intl.NumberFormat(locale, options);
console.log(formatter.format(amount));
http://jsfiddle.net/arturrelax/sa9jL138/1/
More information at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
I know it's an old thread, but I made my own function, which is in pure Javascript.
Simple Solution
https://gist.github.com/VassilisPallas/d73632e9de4794b7dd10b7408f7948e8/bf17eccef8521b4e5869bdc6a5b09a771356fbff
This works fine with finite numbers
function number_format(number, decimals, dec_point, thousands_point) {
if (number == null || !isFinite(number)) {
throw new TypeError("number is not valid");
}
if (!decimals) {
var len = number.toString().split('.').length;
decimals = len > 1 ? len : 0;
}
if (!dec_point) {
dec_point = '.';
}
if (!thousands_point) {
thousands_point = ',';
}
number = parseFloat(number).toFixed(decimals);
number = number.replace(".", dec_point);
var splitNum = number.split(dec_point);
splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_point);
number = splitNum.join(dec_point);
return number;
}
Complex Solution
This solves the issue with big numbers
https://gist.github.com/VassilisPallas/d73632e9de4794b7dd10b7408f7948e8
const splitThousands = (number) => (dec_point, thousands_point) => {
const splitNum = number.toString().split(dec_point);
splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_point);
return splitNum.join(dec_point);
};
const isBigNumber = (number) => number.toString().includes("e");
const isBigFloat = (number) => number.toString().includes("-");
const calcTrailing = (dec, len) => Number(dec) + 2 - len;
const handleBigFloats = (number, decimals) => {
if (!decimals) {
return "0";
}
const [numbers, dec] = number.toString().replace(".", "").split("e-");
const trailingZeros = calcTrailing(dec, numbers.length);
const res = `${"0.".padEnd(trailingZeros + 2, "0")}${numbers}`;
return decimals ? res.substring(0, 2) + res.substring(2, decimals + 2) : res;
};
const handleBigNumbers = (number, decimals, dec_point, thousands_point) => {
if (isBigFloat(number)) {
return handleBigFloats(number, decimals);
}
return splitThousands(BigInt(number))(dec_point, thousands_point);
};
function handleFiniteNumbers(number, decimals, dec_point, thousands_point) {
if (!isFinite(number)) {
throw new TypeError("number is not finite number");
}
if (!decimals) {
const len = number.toString().split(".").length;
decimals = len > 1 ? len : 0;
}
return splitThousands(
parseFloat(number).toFixed(decimals).replace(".", dec_point)
)(dec_point, thousands_point);
}
const numberFormat = (
number,
decimals,
dec_point = ".",
thousands_point = ","
) => {
if (number == null || typeof number !== "number") {
throw new TypeError("number is not valid");
}
if (isBigNumber(number)) {
return handleBigNumbers(number, decimals, dec_point, thousands_point);
}
return handleFiniteNumbers(number, decimals, dec_point, thousands_point);
};
https://jsfiddle.net/p2ft9n4v/1/
Closer function to php number_format($number) should be number.toLocaleString('en') of javascript
Here is another short solution that should behaviour like the php-equivalent.
function number_format(number,decimals,dec_point,thousands_sep) {
number = number*1;//makes sure `number` is numeric value
var str = number.toFixed(decimals?decimals:0).toString().split('.');
var parts = [];
for ( var i=str[0].length; i>0; i-=3 ) {
parts.unshift(str[0].substring(Math.max(0,i-3),i));
}
str[0] = parts.join(thousands_sep?thousands_sep:',');
return str.join(dec_point?dec_point:'.');
}
Here is a simple function that you can use to achieve almost the same result of number_format in php:
function number_format(user_input){
var filtered_number = user_input.replace(/[^0-9]/gi, '');
var length = filtered_number.length;
var breakpoint = 1;
var formated_number = '';
for(i = 1; i <= length; i++){
if(breakpoint > 3){
breakpoint = 1;
formated_number = ',' + formated_number;
}
var next_letter = i + 1;
formated_number = filtered_number.substring(length - i, length - (i - 1)) + formated_number;
breakpoint++;
}
return formated_number;
}
Another way is to use ajax to make a call to a php script where you run number_format on the number and return it with ajax as a string. But it`s a bit messy.
It no easy, try to use simple jquery-plugins such as:
jquery-numberformatter
Jquery-Price-Format
My take on this:
var number_format = function(num) {
stringNum = num.toString();
stringNum = stringNum.split("");
c = 0;
if (stringNum.length>3) {
for (i=stringNum.length; i>-1; i--) {
if ( (c==3) && ((stringNum.length-i)!=stringNum.length) ) {
stringNum.splice(i, 0, ",");
c=0;
}
c++
}
return stringNum;
}
return num;
}
$("body").append(number_format(100000000));
Another variant of exposed examples:
const numberFormat = (value, decimals, decPoint, thousandsSep) => {
decPoint = decPoint || '.';
decimals = decimals !== undefined ? decimals : 2;
thousandsSep = thousandsSep || ' ';
if (typeof value === 'string') {
value = parseFloat(value);
}
let result = value.toLocaleString('en-US', {
maximumFractionDigits: decimals,
minimumFractionDigits: decimals
});
let pieces = result.split('.');
pieces[0] = pieces[0].split(',').join(thousandsSep);
return pieces.join(decPoint);
};
The JS equivalent will be:
var number = //input value
parseFloat(number).toFixed(3);
I'm to do it just calling the JS function as follows and it works:
var formattedNumber = number_format(value)
Is there a simple way to format numbers in JavaScript, similar to the formatting methods available in C# (or VB.NET) via ToString("format_provider") or String.Format()?
Generally
Formatting numbers in JavaScript
Formatting numbers for currency display and more.
In jQuery
autoNumeric (a decent number formatter & input helper with locale support for jQuery 1.5+)
jQuery Format (a clientSide implementation of Java's SimpleDateFormat and NumberFormat)
jquery-numberformatter (number formatter with locale support)
Yes, there is definitely a way to format numbers properly in javascript, for example:
var val=2489.8237
val.toFixed(3) //returns 2489.824 (round up)
val.toFixed(2) //returns 2489.82
val.toFixed(7) //returns 2489.8237000 (padding)
With the use of variablename.toFixed .
And there is another function toPrecision() .
For more detail you also can visit
http://raovishal.blogspot.com/2012/01/number-format-in-javascript.html
Here's a simple JS function to add commas to an integer number in string format. It will handle whole numbers or decimal numbers. You can pass it either a number or a string. It obviously returns a string.
function addCommas(str) {
var parts = (str + "").split("."),
main = parts[0],
len = main.length,
output = "",
first = main.charAt(0),
i;
if (first === '-') {
main = main.slice(1);
len = main.length;
} else {
first = "";
}
i = len - 1;
while(i >= 0) {
output = main.charAt(i) + output;
if ((len - i) % 3 === 0 && i > 0) {
output = "," + output;
}
--i;
}
// put sign back
output = first + output;
// put decimal part back
if (parts.length > 1) {
output += "." + parts[1];
}
return output;
}
Here's a set of test cases: http://jsfiddle.net/jfriend00/6y57j/
You can see it being used in this previous jsFiddle: http://jsfiddle.net/jfriend00/sMnjT/. You can find functions that will handle decimal numbers too with a simple Google search for "javascript add commas".
Converting a number to a string can be done many ways. The easiest is just to add it to a string:
var myNumber = 3;
var myStr = "" + myNumber; // "3"
Within, the context of your jsFiddle, you'd get commas into the counter by changing this line:
jTarget.text(current);
to this:
jTarget.text(addCommas(current));
You can see it working here: http://jsfiddle.net/jfriend00/CbjSX/
I wrote a simple function (not yet another jQuery plugin needed!!) that converts a number to a decimal separated string or an empty string if the number wasn't a number to begin with:
function format(x) {
return isNaN(x)?"":x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
format(578999); results in 578,999
format(10); results in 10
if you want to have a decimal point instead of a comma simply replace the comma in the code with a decimal point.
One of the comments correctly stated this only works for integers, with a few small adaptions you can make it work for floating points as well:
function format(x) {
if(isNaN(x))return "";
n= x.toString().split('.');
return n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")+(n.length>1?"."+n[1]:"");
}
Here are some solutions, all pass the test suite, test suite and benchmark included, if you want copy and paste to test, try This Gist.
Method 0 (RegExp)
Base on https://stackoverflow.com/a/14428340/1877620, but fix if there is no decimal point.
if (typeof Number.prototype.format === 'undefined') {
Number.prototype.format = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.');
a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
return a.join('.');
}
}
Method 1
if (typeof Number.prototype.format1 === 'undefined') {
Number.prototype.format1 = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.'),
// skip the '-' sign
head = Number(this < 0);
// skip the digits that's before the first thousands separator
head += (a[0].length - head) % 3 || 3;
a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
return a.join('.');
};
}
Method 2 (Split to Array)
if (typeof Number.prototype.format2 === 'undefined') {
Number.prototype.format2 = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.');
a[0] = a[0]
.split('').reverse().join('')
.replace(/\d{3}(?=\d)/g, '$&,')
.split('').reverse().join('');
return a.join('.');
};
}
Method 3 (Loop)
if (typeof Number.prototype.format3 === 'undefined') {
Number.prototype.format3 = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('');
a.push('.');
var i = a.indexOf('.') - 3;
while (i > 0 && a[i-1] !== '-') {
a.splice(i, 0, ',');
i -= 3;
}
a.pop();
return a.join('');
};
}
Example
console.log('======== Demo ========')
var n = 0;
for (var i=1; i<20; i++) {
n = (n * 10) + (i % 10)/100;
console.log(n.format(2), (-n).format(2));
}
Separator
If we want custom thousands separator or decimal separator, use replace():
123456.78.format(2).replace(',', ' ').replace('.', ' ');
Test suite
function assertEqual(a, b) {
if (a !== b) {
throw a + ' !== ' + b;
}
}
function test(format_function) {
console.log(format_function);
assertEqual('NaN', format_function.call(NaN, 0))
assertEqual('Infinity', format_function.call(Infinity, 0))
assertEqual('-Infinity', format_function.call(-Infinity, 0))
assertEqual('0', format_function.call(0, 0))
assertEqual('0.00', format_function.call(0, 2))
assertEqual('1', format_function.call(1, 0))
assertEqual('-1', format_function.call(-1, 0))
// decimal padding
assertEqual('1.00', format_function.call(1, 2))
assertEqual('-1.00', format_function.call(-1, 2))
// decimal rounding
assertEqual('0.12', format_function.call(0.123456, 2))
assertEqual('0.1235', format_function.call(0.123456, 4))
assertEqual('-0.12', format_function.call(-0.123456, 2))
assertEqual('-0.1235', format_function.call(-0.123456, 4))
// thousands separator
assertEqual('1,234', format_function.call(1234.123456, 0))
assertEqual('12,345', format_function.call(12345.123456, 0))
assertEqual('123,456', format_function.call(123456.123456, 0))
assertEqual('1,234,567', format_function.call(1234567.123456, 0))
assertEqual('12,345,678', format_function.call(12345678.123456, 0))
assertEqual('123,456,789', format_function.call(123456789.123456, 0))
assertEqual('-1,234', format_function.call(-1234.123456, 0))
assertEqual('-12,345', format_function.call(-12345.123456, 0))
assertEqual('-123,456', format_function.call(-123456.123456, 0))
assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
// thousands separator and decimal
assertEqual('1,234.12', format_function.call(1234.123456, 2))
assertEqual('12,345.12', format_function.call(12345.123456, 2))
assertEqual('123,456.12', format_function.call(123456.123456, 2))
assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}
console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);
Benchmark
function benchmark(f) {
var start = new Date().getTime();
f();
return new Date().getTime() - start;
}
function benchmark_format(f) {
console.log(f);
time = benchmark(function () {
for (var i = 0; i < 100000; i++) {
f.call(123456789, 0);
f.call(123456789, 2);
}
});
console.log(time.format(0) + 'ms');
}
async = [];
function next() {
setTimeout(function () {
f = async.shift();
f && f();
next();
}, 10);
}
console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
async.push(function () { benchmark_format(Number.prototype.format1); });
async.push(function () { benchmark_format(Number.prototype.format2); });
async.push(function () { benchmark_format(Number.prototype.format3); });
next();
If you don't want to use jQuery, take a look at Numeral.js
Firstly, converting an integer into string in JS is really simple:
// Start off with a number
var number = 42;
// Convert into a string by appending an empty (or whatever you like as a string) to it
var string = 42+'';
// No extra conversion is needed, even though you could actually do
var alsoString = number.toString();
If you have a number as a string and want it to be turned to an integer, you have to use the parseInt(string) for integers and parseFloat(string) for floats. Both of these functions then return the desired integer/float. Example:
// Start off with a float as a string
var stringFloat = '3.14';
// And an int as a string
var stringInt = '42';
// typeof stringInt would give you 'string'
// Get the real float from the string
var realFloat = parseFloat(someFloat);
// Same for the int
var realInt = parseInt(stringInt);
// but typeof realInt will now give you 'number'
What exactly are you trying to append etc, remains unclear to me from your question.
http://code.google.com/p/javascript-number-formatter/ :
Short, fast, flexible yet standalone. Only 75 lines including MIT license info, blank lines & comments.
Accept standard number formatting like #,##0.00 or with negation -000.####.
Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol.
Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.
Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.
Auto number rounding.
Simple interface, just supply mask & value like this: format( "0.0000", 3.141592)
UPDATE
As say Tomáš Zato here one line solution:
(666.0).toLocaleString()
numObj.toLocaleString([locales [, options]])
which described in ECMA-262 5.1 Edition:
http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.3
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
and will work in future versions of browsers...
For example:
var flt = '5.99';
var nt = '6';
var rflt = parseFloat(flt);
var rnt = parseInt(nt);
Using JQuery.
$(document).ready(function()
{
//Only number and one dot
function onlyDecimal(element, decimals)
{
$(element).keypress(function(event)
{
num = $(this).val() ;
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
if($(this).val() == parseFloat(num).toFixed(decimals))
{
event.preventDefault();
}
});
}
onlyDecimal("#TextBox1", 3) ;
});
To get a decimal with 2 numbers after the comma, you could just use:
function nformat(a) {
var b = parseInt(parseFloat(a)*100)/100;
return b.toFixed(2);
}
May I suggest numbro for locale based formatting and number-format.js for the general case. A combination of the two depending on use-case may help.
Here's another version:
$.fn.digits = function () {
return this.each(function () {
var value = $(this).text();
var decimal = "";
if (value) {
var pos = value.indexOf(".");
if (pos >= 0) {
decimal = value.substring(pos);
value = value.substring(0, pos);
}
if (value) {
value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
$(this).text(value);
}
}
else {
value = $(this).val()
if (value) {
var pos = value.indexOf(".");
if (pos >= 0) {
decimal = value.substring(pos);
value = value.substring(0, pos);
}
if (value) {
value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
$(this).val(value);
}
}
}
})
};
I made a simple function, maybe someone can use it
function secsToTime(secs){
function format(number){
if(number===0){
return '00';
}else {
if (number < 10) {
return '0' + number
} else{
return ''+number;
}
}
}
var minutes = Math.floor(secs/60)%60;
var hours = Math.floor(secs/(60*60))%24;
var days = Math.floor(secs/(60*60*24));
var seconds = Math.floor(secs)%60;
return (days>0? days+"d " : "")+format(hours)+':'+format(minutes)+':'+format(seconds);
}
this can generate the followings outputs:
5d 02:53:39
4d 22:15:16
03:01:05
00:00:00
In case you want to format number for view rather than for calculation you can use this
function numberFormat( number ){
var digitCount = (number+"").length;
var formatedNumber = number+"";
var ind = digitCount%3 || 3;
var temparr = formatedNumber.split('');
if( digitCount > 3 && digitCount <= 6 ){
temparr.splice(ind,0,',');
formatedNumber = temparr.join('');
}else if (digitCount >= 7 && digitCount <= 15) {
var temparr2 = temparr.slice(0, ind);
temparr2.push(',');
temparr2.push(temparr[ind]);
temparr2.push(temparr[ind + 1]);
// temparr2.push( temparr[ind + 2] );
if (digitCount >= 7 && digitCount <= 9) {
temparr2.push(" million");
} else if (digitCount >= 10 && digitCount <= 12) {
temparr2.push(" billion");
} else if (digitCount >= 13 && digitCount <= 15) {
temparr2.push(" trillion");
}
formatedNumber = temparr2.join('');
}
return formatedNumber;
}
Input: {Integer} Number
Outputs: {String} Number
22,870 => if number 22870
22,87 million => if number 2287xxxx (x can be whatever)
22,87 billion => if number 2287xxxxxxx
22,87 trillion => if number 2287xxxxxxxxxx
You get the idea
To further jfriend00's answer (I dont't have enough points to comment) I have extended his/her answer to the following:
function log(args) {
var str = "";
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === "object") {
str += JSON.stringify(arguments[i]);
} else {
str += arguments[i];
}
}
var div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
}
Number.prototype.addCommas = function (str) {
if (str === undefined) {
str = this;
}
var parts = (str + "").split("."),
main = parts[0],
len = main.length,
output = "",
first = main.charAt(0),
i;
if (first === '-') {
main = main.slice(1);
len = main.length;
} else {
first = "";
}
i = len - 1;
while(i >= 0) {
output = main.charAt(i) + output;
if ((len - i) % 3 === 0 && i > 0) {
output = "," + output;
}
--i;
}
// put sign back
output = first + output;
// put decimal part back
if (parts.length > 1) {
output += "." + parts[1];
}
return output;
}
var testCases = [
1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,
-1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1
];
for (var i = 0; i < testCases.length; i++) {
log(testCases[i].addCommas());
}
/*for (var i = 0; i < testCases.length; i++) {
log(Number.addCommas(testCases[i]));
}*/
You can do it in the following way:
So you will not only format the number but you can also pass as a parameter how many decimal digits to display, you set a custom decimal and mile separator.
function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
const roundedNumber = number.toFixed(decimals);
let integerPart = '', fractionalPart = '';
if (decimals == 0) {
integerPart = roundedNumber;
decimalSeparator = '';
} else {
let numberParts = roundedNumber.split('.');
integerPart = numberParts[0];
fractionalPart = numberParts[1];
}
integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
return `${integerPart}${decimalSeparator}${fractionalPart}`;
}
Use:
let min = 1556454.0001;
let max = 15556982.9999;
console.time('number format');
for (let i = 0; i < 15000; i++) {
let randomNumber = Math.random() * (max - min) + min;
let formated = format(randomNumber, 4, ',', '.'); // formated number
console.debug('number: ', randomNumber, 'formated: ', formated);
}
console.timeEnd('number format');