Converting math equation from PHP to Javascript (Jquery) - php

I've been working on getting a Coefficient of Variation equation ported from PHP to Javascript, but can't seem to get it working.
Original PHP script:
// define variables, strip spaces
$weights = $_POST['weights'];
// define coefficient of variation function
function cv($array){
$n = 0;
$mean = 0;
$M2 = 0;
foreach($array as $x){
if ($x != NULL AND $x != '') {
$n++;
$delta = $x - $mean;
$mean = $mean + $delta/$n;
$M2 = $M2 + $delta*($x - $mean);
$total = $total + $x;
}
}
return (((sqrt($M2/($n - 1))) / ($total/$n))*100);
}
$cv = (cv($weights));
This basically takes an array, and figures out the coefficient of variation for it. Now as I try to convert it to Javascript via some Jquery function:
var fields = $('#cvform').serializeArray();
var count = 0;
var num = 0;
var mean = 0;
var m2 = 0;
var total = 0;
var delta = 0;
jQuery.each(fields, function(i, field){
if (field.value > 0) {
num++;
delta=(field.value-mean);
mean=(mean+delta/num);
m2=(m2+delta*(field.value-mean));
total=(total+field.value);
};
});
var cov=(((Math.sqrt(m2/(num-1)))/(total/num))*100);
$("<span>Coefficient of Variation: " + cov + "</span>").appendTo('#cvdisplay');
While the javascript function outputs an answer, it is not correct. If I enter the values "3,3,2,3,3,4" the PHP script gives an output of 21.08, which is correct. The javascript function gives me the value of 0.0011418432035849642.
Can anyone point me to where the equations are differing?

You need to convert your array values to floats via parseFloat() (or integers, parseInt(), whatever suits you):
var fields = $('#cvform').serializeArray();
var count = 0;
var num = 0;
var mean = 0;
var m2 = 0;
var total = 0;
var delta = 0;
$.each(fields, function(i, field) {
alert(field.value);
if (parseFloat(field.value) > 0) {
num++;
delta = (parseFloat(field.value) - mean);
mean = (mean + delta / num);
m2 = (m2 + delta * (parseFloat(field.value) - mean));
total = (total + parseFloat(field.value));
}
});
var cov = (((Math.sqrt(m2 / (num - 1))) / (total / num)) * 100);
$("<span>Coefficient of Variation: " + cov + "</span>").appendTo('#cvdisplay');

The issue is the javascript line
total=(total+field.value); which results in 0332334 instead of 18 as expected. String concatenation is being applied instead of numeric addition.
You can fix this by parsing the integer value: total += parseInt(field.value);

function stDeviation(array){
var L= array.length,
mean= array.reduce(function(a, b){
return a+b;
})/L,
dev= array.map(function(itm){
var tem= itm-mean;
return tem*tem;
});
return Math.sqrt(dev.reduce(function(a, b){
return a+b;
})/L);
}
Math.mean= function(array){
return array.reduce(function(a, b){ return a+b; })/array.length;
}
Math.stDeviation=function(array){
var mean= Math.mean(array);
dev= array.map(function(itm){return (itm-mean)*(itm-mean); });
return Math.sqrt(dev.reduce(function(a, b){ return a+b; })/array.length);
}
var A2= [6.2, 5, 4.5, 6, 6, 6.9, 6.4, 7.5];
alert ('mean: '+Math.mean(A2)+'; deviation: '+Math.stDeviation(A2))

Here, I changed the code around a bit and got it to work. I basically isolated the segments a bit more. Made it more direct.
<?php
$weights = Array(3,3,2,3,3,4);
// define coefficient of variation function
function cv($array) {
$n = 0;
$mean = 0;
$M2 = 0;
$total = 0;
foreach($array as $x) {
if ( !empty($x) ) {
$n++;
$delta = $x - $mean;
$mean = $mean + $delta / $n;
$M2 = $M2 + $delta * ($x - $mean);
$total = $total + $x;
}
}
$sqrt = sqrt( $M2 / ($n - 1) );
$tn = $total / $n;
echo "Sqrt is $sqrt tn is $tn";
return ( $sqrt / $tn ) * 100;
}
$cv = cv($weights);
?>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var fields = Array(3,3,2,3,3,4);
var count = 0;
var n = 0;
var mean = 0;
var m2 = 0;
var total = 0;
var delta = 0;
jQuery.each(fields, function(i, field) {
//var x = field.value;
var x = 1 * field;
if (x > 0) {
n++;
delta = (x - mean);
mean = (mean + (delta / n));
m2 = (m2 + delta * (x - mean));
total = (total + x);
};
});
var sqrt = Math.sqrt(m2 / (n - 1));
var tn = total / n;
var cov = ((sqrt / tn) * 100);
console.log("Total is: "+ total);
console.log("Sqrt is " + sqrt + " tn is " + tn + " cov is " + cov);
$('#js').text("JS Output is: " + cov);
});
</script>
</head>
<body>
<div>
<div>PHP Output: <?=$cv;?></div>
<div id="js"></div>
</div>
</body>
</html>

Here's a direct translation of the function you provided. You have to pass in a javascript array of numbers, and it produces the result you're looking for (at least according to unit tests written in Node.js). You should to the type conversion (string-to-array) in another function to separate your concerns and make the code easier to reason about;
var CoV = function(ary) {
var mean = 0,
n = 0,
m2 = 0,
total = 0,
delta;
for(var i = 0, l = ary.length; i < l; i += 1) {
n += 1;
delta = ary[i] - mean;
mean = mean + delta / n;
m2 = m2 + delta * (ary[i] - mean)
total = total + ary[i]
}
console.log(mean);
console.log(m2);
console.log(total);
return ((Math.sqrt(m2/(i - 1))) / (total / i)) * 100;
};

Related

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

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!

jQuery ONLY hour and seconds countdown

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);
};`

my javascript freeze the screen and there is no mistake, just the navigator does not work

I met trouble with a script I have done,
this script should allocate an amount to different fields.
In fact here is the script, I will give you after the jsfiddle.
<script type="text/javascript">
function getItems()
{
var items = new Array();
var itemCount = document.getElementsByClassName("items");
for(var i = 0; i < itemCount.length; i++)
{
items[i] = document.getElementById("p"+(i+1)).value;
}
return items;
}
function setItems(items,payAmt)
{
//document.getElementById("troppercu").value = payAmt;
for(var i = 0; i < items.length; i++)
{
document.getElementById("p" + (i+1)).value = items[i];
}
}
function itemSum(items)
{
var sum = 0;
for(var i=0; i < items.length; i++)
{
sum = items[i] + sum;
}
return sum;
}
function payment(inputElm)
{
var items = getItems();
var payAmt = document.getElementById("montantacompte").value;
var i = 0;
var sum = itemSum(items);
while(payAmt != 0 && sum != 0)
{
var temp = items[i] - payAmt;
if(temp > 0)
{
items[i] = Math.round((temp)*100)/100;
break;
}
else if(temp < 0)
{
items[i] = 0;
payAmt = temp*-1;
}
i++;
sum = itemSum(items);
}
setItems(items, payAmt);
}
</script>
So I have an input in which I can write an amount, this amount will be allocated on the different fields.
Actually, the trouble is that when I put an amount that is the same as the principal amount, it freezes the screen. If I write the same amount + 1 cent, it does not freeze.
All information on the fields come from my database. that is written with PHP and MySQL.
http://jsfiddle.net/ywAU3/
The trouble comes when you write the same amount as in the principal so for that case it will freeze the screen if you write on the yellow box input 3654.58 I really do not understand why, in fact, it should not, because if I write 3654.59 all works, If I write more, it works also.
The values you are passing into this function are strings, not numbers
function itemSum(items){
var sum = 0;
for(var i=0; i < items.length; i++){
sum = items[i] + sum;
}
return sum;
}
The value of 'sum' is turned into a long concatenated set of strings, not numbers.
The problem is in while cycle,
you have
if(temp > 0)
and
else if(temp < 0)
But what if
temp=0
That causes your while cycle to work forever... I included temp = 0 case and then code worked fine:
http://jsfiddle.net/ywAU3/2/

What is the JS equivalent to the PHP function number_format?

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)

JavaScript function that can produce same results as PHP function number_format [duplicate]

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');

Categories