Use PHP functions in JavaScript

JavaScript round

Returns the number rounded to specified precision

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
55
function round (value, precision, mode) {
    // Returns the number rounded to specified precision  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/round    // +   original by: Philip Peterson
    // +    revised by: Onno Marsman
    // +      input by: Greenseed
    // +    revised by: T.Wild
    // +      input by: meo    // +      input by: William
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Josep Sanz (http://www.ws3.es/)
    // +    revised by: Rafał Kukawski (http://blog.kukawski.pl/)
    // %        note 1: Great work. Ideas for improvement:    // %        note 1:  - code more compliant with developer guidelines
    // %        note 1:  - for implementing PHP constant arguments look at
    // %        note 1:  the pathinfo() function, it offers the greatest
    // %        note 1:  flexibility & compatibility possible
    // *     example 1: round(1241757, -3);    // *     returns 1: 1242000
    // *     example 2: round(3.6);
    // *     returns 2: 4
    // *     example 3: round(2.835, 2);
    // *     returns 3: 2.84    // *     example 4: round(1.1749999999999, 2);
    // *     returns 4: 1.17
    // *     example 5: round(58551.799999999996, 2);
    // *     returns 5: 58551.8
    var m, f, isHalf, sgn; // helper variables    precision |= 0; // making sure precision is integer
    m = Math.pow(10, precision);
    value *= m;
    sgn = (value > 0) | -(value < 0); // sign of the number
    isHalf = value % 1 === 0.5 * sgn;    f = Math.floor(value);
 
    if (isHalf) {
        switch (mode) {
        case 'PHP_ROUND_HALF_DOWN':            value = f + (sgn < 0); // rounds .5 toward zero
            break;
        case 'PHP_ROUND_HALF_EVEN':
            value = f + (f % 2 * sgn); // rouds .5 towards the next even integer
            break;        case 'PHP_ROUND_HALF_ODD':
            value = f + !(f % 2); // rounds .5 towards the next odd integer
            break;
        default:
            value = f + (sgn > 0); // rounds .5 away from zero        }
    }
 
    return (isHalf ? value : Math.round(value)) / m;
}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
round(1241757, -3);

Should return

1
1242000

» Example 2

Running

1
round(3.6);

Should return

1
4

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have round goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
max4ever
11 Oct '11 Permalink

q  this one is tiny and works (doesn't support the php_round_... variables though) http://stackoverflow.com/questions/6437062/javascript-vs-php-rounding/6438281#6438281

Gravatar
Mickey
29 Mar '11 Permalink

q  Just realized that I "killed" the function for integers.

if(String(value).lastIndexOf(".") < 0) {
    value *= m;
} else {
    // my posted code
}



:)

Gravatar
Mickey
29 Mar '11 Permalink

q  Hello!

Thank you for this. But... I found some examples where this gives inaccurate results:

round(162.295, 2); //gives 162.29
round(613.305, 2); //gives 613.3



The problem is multiplying by power of ten gives:

162.295 * 100; //gives 16229.499999999998



There is one more, but the result is OK:

162.395 * 100; //gives 16239.500000000002



I changed (line 33):

value *= m;



with this:


var stringValue = String(value);
var newDecimalPlace = stringValue.lastIndexOf(".") + precision;
stringValue = stringValue.replace(".", "");
if (newDecimalPlace < 0) {
var tempStringValue = "0.";
for (var i = newDecimalPlace; i < 0; i++) {
tempStringValue += "0";
}
value = Number(tempStringValue + stringValue);
} else {
value = Number(stringValue.substr(0, newDecimalPlace) + "." + stringValue.substr(newDecimalPlace));
}



Basically I multiply by power of 10 by moving the "." in the number converted to a string. If "precision" is negative - pad the number with "0." and needed number of zeros, otherwise - place the "." in new place.

It works for examples I found.

Thanks.

Gravatar
Josep Sanz
10 Sep '10 Permalink

q  I update the php.js library to the lastest version and the round function work as expected.

Thanks Rafał Kukawski.

Josep.

Gravatar
Kevin van Zonneveld
8 Sep '10 Permalink

q  @ Josep Sanz: Rafał Kukawski has fixed your issue!

@ Rafał Kukawski: Thanks, this one is much better. All current tests (found in the example comment blocks) pass!
https://github.com/kvz/phpjs/commit/9d563a56bcc28c290a6148ffcbd37e3052cee523

PS
If you'd like commit access to our github repository, drop me a line kvz@php.net

Gravatar
Rafał Kukawski
4 Sep '10 Permalink

q  BTW. while doing basic tests I compared the results with PHP 5.3.1.

Gravatar
Rafał Kukawski
4 Sep '10 Permalink

q  Didn't test it much, but this is my implementation of the function.

function round(value, precision, mode){
	var m, f, isHalf, sgn; // helper variables
	precision |= 0; // making sure precision is integer
	m = Math.pow(10, precision);
	value *= m;
	sgn = (value>0)|-(value<0); // sign of the number
	isHalf = value % 1 === 0.5 * sgn;
	f = Math.floor(value);
	
	if(isHalf){
		switch(mode){
			case 'PHP_ROUND_HALF_DOWN':
				value = f + (sgn < 0); // rounds .5 toward zero
				break;
			case 'PHP_ROUND_HALF_EVEN':
				value = f + (f % 2 * sgn); // rouds .5 towards the next even integer
				break;
			case 'PHP_ROUND_HALF_ODD':
				value = f + !(f % 2); // rounds .5 towards the next odd integer
				break;
			default:
				value = f + (sgn > 0); // rounds .5 away from zero
		}
	}
	
	return (isHalf ? value : Math.round(value)) / m;
}



I'll try to prepare some unit tests today and test this function.

Gravatar
Josep Sanz
2 Sep '10 Permalink

q  Hi PHPJS team.

I detect an error:

round(58551.799999999996,2) 
returns 58551.799999999996



If I change the precision to 1 or 3, work as expected

Thanks.

Gravatar
Brett Zamir
20 Apr '10 Permalink

q  @gaurav: Please try with the latest version at http://github.com/kvz/phpjs/raw/master/functions/math/round.js and see if that works as we made a fix here recently...

Gravatar
gaurav
20 Apr '10 Permalink

q  this function rounds "1236.0000000000002" to 123.12.

how shall I solve this problem.

Gravatar
Brett Zamir
3 Apr '10 Permalink

q  @William: What's missing is a digit, and I don't mean a finger or a toe... The code had problems when the first digit was 0 or when the number to be rounded up was 9, now fixed in Git; see http://github.com/kvz/phpjs/raw/master/functions/math/round.js . Nice test, btw... and thanks! :)

Gravatar
William
2 Apr '10 Permalink

q  round(179.06) = 17?

What am I missing here?

while (mynum < 300)
{
	mynum += Math.random();
	if (round(mynum) != Math.round(mynum))
		document.getElementsByTagName('body')[0].innerHTML += '<br>'+mynum+' '+round(mynum)+' '+Math.round(mynum);
}

Gravatar
Brett Zamir
9 Jan '10 Permalink

q  @kadimi: Thank you for offering your shorter version. Since we're offering the full PHP API (with all three arguments), more was necessary... If you can reimplement in a shorter form than ours and still fully support all 3 arguments (without adding processing), we'd be all for it...In any case, maybe your version will be of interest to others who don't care about the full API...

Gravatar
kadimi
9 Jan '10 Permalink

q  My tiny version... lol

function round_float(x,n){
  if(arguments.length < 2 || !parseInt(n))
  	var n=0;
  if(!parseFloat(x))
  	return false;
  return Math.round(x*Math.pow(10,n))/Math.pow(10,n);
}

Gravatar
Kevin van Zonneveld
14 Dec '09 Permalink

q  @ meo: I've added testcases to confirm your issue:
http://github.com/kvz/phpjs/commit/c8dda288ef6f4e1a5c803c7e7338e460a6ca006e

Try with

1.1749999999999 // 13 digits


and php still gives the correct

1.17



Try with

1.17499999999999 // 14 digits


and php gives the 'incorrect'

1.18



Both on my 32 bits as my 64 bits system, PHP messes it up and turns the last number into 1.18.

So it looks like PHP is simplifying the number as it gets 14 decimal digits. I checked here http://php.net/manual/en/language.types.float.php and my suspicion was confirmed: "The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format)."

So even though this is a gray array, we may need to consider to break round on purpose, just to make it complient with PHP.

Thoughts?

Gravatar
meo
9 Nov '09 Permalink

q  Correction! For on step rounding like before it works, but for the following.

round(1.1749999999999998, 2);



returns 1.18 on php and 1.17 on JavaScript. Sorry about the previous post.

Gravatar
meo
9 Nov '09 Permalink

q  when I round:

round(0.175, 2); 



I get 0.17 instead of 0.18 in php round, what could be wrong?

Gravatar
meo
9 Nov '09 Permalink

q  when I round round(0.175, 2); I get 0.17 instead of 0.178 in php round, what could be wrong?

Gravatar
Kevin van Zonneveld
4 Aug '09 Permalink

q  @ T.Wild: Great job!
(for the record: I like http://phpjs.org/functions/pathinfo:486 's way of handling constant arguments best)

Gravatar
Brett Zamir
29 Jul '09 Permalink

q  @T. Wild: I've added your changes, with some whitespace clean-up, capitalization changes (initial-capitalized generally represent constructors, while full-capitalized generally represent constants), and removed the comment about the constant values being unknown, since you had the correct numeric values per the PHP source
@Kevin: It looks ready to be applied the next time we update.

Gravatar
T.Wild
28 Jul '09 Permalink

q  O.K, re-written version of my round function, I really should learn how to test better and actually double check returned values :) anyway, this version appears to work and implements round half up, half down, half even and half odd.

I removed ceiling, floor, up and down since their not mentioned in the PHP manual.

any further suggestions are welcome.

[CODE]
function round (val, precision, mode) {
// http://kevin.vanzonneveld.net
// + original by: Philip Peterson
// + revised by: Onno Marsman
// + input by: Greenseed
// + revised by: T.Wild
// % note 1: Great work. Ideas for improvement:
// % note 1: - code more compliant with developer guidelines
// % note 1: - for implementing PHP constant arguments look at
// % note 1: the pathinfo() function, it offers the greatest
// % note 1: flexibility & compatibility possible
// * example 1: round(1241757, -3);
// * returns 1: 1242000
// * example 2: round(3.6);
// * returns 2: 4
// * example 3: round(2.835,2);
// * returns 3: 2.84

/*Declare Variables
* Retval - temporay holder of the value to be returned
* V - String representation of val
* integer - Integer portion of val
* decimal - decimal portion of val
* decp - characterindex of . [decimal point] inV
* negative- was val a negative value?
*
* ROUND_HALF_OE - Rounding function for ROUND_HALF_ODD and ROUND_HALF_EVEN
* ROUND_HALF_UD - Rounding function for ROUND_HALF_UP and ROUND_HALF_DOWN
* ROUND_HALF - Primary function for round half rounding modes
*/
var RetVal=0,V='',integer='',decimal='',decp=0,negative=false;
var ROUND_HALF_OE = function(DtR,DtLa,even){
if(even === true){
if(DtLa == 50){
if((DtR % 2) === 1){
if(DtLa >= 5){
DtR+=1;
}else{
DtR-=1;
}
}
}else if(DtLa >= 5){
DtR+=1;
}
}else{
if(DtLa == 5){
if((DtR % 2) === 0){
if(DtLa >= 5){
DtR+=1;
}else{
DtR-=1;
}
}
}else if(DtLa >= 5){
DtR+=1;
}
}
return DtR;
};
var ROUND_HALF_UD = function(DtR,DtLa,up){
if(up === true){
if(DtLa>=5){
DtR+=1;
}
}else{
if(DtLa>5){
DtR+=1;
}
}
return DtR;
};
var ROUND_HALF = function(Val,Decplaces,mode){
/*Declare variables
*V - string representation of Val
*Vlen - The length of V - used only when rounding intgerers
*VlenDif - The difference between the lengths of the original V
* and the V after being truncated
*decp - character in index of . [decimal place] in V
*integer - Integr protion of Val
*decimal - Decimal portion of Val
*DigitToRound - The digit to round
*DigitToLookAt- The digit to comapre when rounding
*
*round - A function to do the rounding
*/
var V = Val.toString(),Vlen=0,VlenDif=0;
var decp = V.indexOf('.');
var DigitToRound = 0,DigitToLookAt = 0;
var integer='',decimal='';
var round = null,bool=false;
switch(mode){
case 'up':
bool = true;
case 'down':
round = ROUND_HALF_UD;
break;
case 'even':
bool = true;
case 'odd':
round = ROUND_HALF_OE;
break;
}
if (Decplaces < 0){ //Int round
Vlen=V.length;
Decplaces = Vlen + Decplaces;
DigitToLookAt = Number(V.charAt(Decplaces));
DigitToRound = Number(V.charAt(Decplaces-1));
DigitToRound = round(DigitToRound,DigitToLookAt,bool);
V = V.slice(0,Decplaces-1);
VlenDif = Vlen-V.length-1;
if (DigitToRound == 10){
V = String(Number(V)+1)+"0";
}else{
V+=DigitToRound;
}
V = Number(V)*(Math.pow(10,VlenDif));
}else if(Decplaces > 0){
integer=V.slice(0,decp);
decimal=V.slice(decp+1);
DigitToLookAt = Number(decimal.charAt(Decplaces));
DigitToRound = Number(decimal.charAt(Decplaces-1));
DigitToRound = round(DigitToRound,DigitToLookAt,bool);
decimal=decimal.slice(0,Decplaces-1);
if(DigitToRound==10){
V=Number(integer+'.'+decimal)+(1*(Math.pow(10,(0-decimal.length))));
}else{
V=Number(integer+'.'+decimal+DigitToRound);
}
}else{
integer=V.slice(0,decp);
decimal=V.slice(decp+1);
DigitToLookAt = Number(decimal.charAt(Decplaces));
DigitToRound = Number(integer.charAt(integer.length-1));
DigitToRound = round(DigitToRound,DigitToLookAt,bool);
decimal='0';
integer = integer.slice(0,integer.length-1);
if(DigitToRound==10){
V=Number(integer)+1;
}else{
V=Number(integer+DigitToRound);
}
}
return V;
};

//precision optional - defaults 0
if (typeof precision == 'undefined') {
precision = 0;
}
//mode optional - defaults round half up
if (typeof mode == 'undefined') {
mode = 'PHP_ROUND_HALF_UP';
}

if (val < 0){ //Remember if val is negative
negative = true;
}else{
negative = false;
}

V = Math.abs(val).toString(); //Take a string representation of val
decp = V.indexOf('.'); //And locate the decimal point
if ((decp == -1) && (precision >=0)){
/* If there is no deciaml point and the precision is greater than 0
* there is no need to round, return val
*/
return val;
}else{
if (decp == -1){
//There are no decimals so intger=V and decimal=0
integer = V;
decimal = '0';
}else{
//Otherwise we have to split the decimals from the integer
integer = V.slice(0,decp);
if(precision >= 0){
//If the precision is greater than 0 then split the decimals from the integer
//We truncate the decimals to a number of places equal to the precision requested+1
decimal = V.substr(decp+1,precision+1);
}else{
//If the precision is less than 0 ignore the decimals - set to 0
decimal = '0';
}
}
if ((precision > 0) && (precision >= decimal.length)){
/*If the precision requested is more decimal places than already exist
*there is no need to round - return val
*/
return val;
}else if ((precision < 0) && (Math.abs(precision) >= integer.length)){
/*If the precison is less than 0, and is greater than than the
*number of digits in integer, return 0 - mimics PHP
*/
return 0;
}
val = Number(integer+'.'+decimal); //After sanitizing recreate val,
}

//Call approriate function based on passed mode, fall through for integer constants
//INTEGER VALUES MAY NOT BE CORRECT, UNABLE TO VERIFY WITHOUT PHP 5.3//
switch (mode){
case 0:
case 'PHP_ROUND_HALF_UP':
RetVal = ROUND_HALF(val,precision,'up');
break;
case 1:
case 'PHP_ROUND_HALF_DOWN':
RetVal = ROUND_HALF(val, precision,'down');
break;
case 2:
case 'PHP_ROUND_HALF_EVEN':
RetVal = ROUND_HALF(val,precision,'even');
break;
case 3:
case 'PHP_ROUND_HALF_ODD':
RetVal = ROUND_HALF(val,precision,'odd');
break;
}
if(negative){
return 0-RetVal;
}else{
return RetVal;
}
}
[CODE]

Gravatar
Kevin van Zonneveld
14 Jul '09 Permalink

q  ohyeah:
@ Greenseed: Thanks for helping us out!

@ T. Wild: PS, you can have a look at the source here:
http://trac.plutonia.nl/projects/phpjs/browser/trunk/functions/math/round.js
I'll actually deploy it to the site when all test-cases pass.

Gravatar
Kevin van Zonneveld
14 Jul '09 Permalink

q  @ T.Wild: Thanks a lot for really going out of your way to make this solid! I added Greenseed's testcase and it passes. The first function example currently fails though, you may want to look at that if you feel like it. Other than that: Great stuff T. Wild! Awesome.

Gravatar
T.Wild
12 Jul '09 Permalink

q  A slight oversight on my part,
you'll need to add
if(typeof precision == 'undefined'){precision = 0;}
to the line before
decp = V.indexOf('.');
to account for a precision not being past to the function.

Gravatar
T.Wild
12 Jul '09 Permalink

q  A round implementation with support for:
PHP_ROUND_UP, PHP_ROUND_DOWN, PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_FLOOR, PHP_ROUND_CEILING
using http://publib.boulder.ibm.com/infocenter/wmbhelp/v6r0m0/index.jsp?topic=/com.ibm.etools.mft.doc/ak05380_.htm as reference,

It's not pretty but as far as I can tell it works, passes the tests I've thrown at it anyway :)
**can't fully test, don't have PHP 5.3 yet**

The only reason I haven't implemented PHP_ROUND_HALF_EVEN is the example I have to work on only uses 1 dp with a precision of 0, so I don't know what it's meant to do if there are multiple dps.

function round( val, precision, mode ) {
    var V = val.toString(),integer,decimal,reint = false,decp,d1,d2,pow=0; //Define variables.
    decp = V.indexOf('.'); //Find index of decimal place
    if (decp == -1){ //If there is no decimal place we are most likely dealing with an integer
        /*---ROUNDING AN INTEGER---
         * If the precision is 0 then we don't need to round
         * otherwise turn the integer into a decimal E.G
         * 100 becomes 0.1
         * 2143 becomes 0.2143
         * take the modulus of the precision and then round the decimal
         * we turn it back into an intgeger at the end
         */
        if (precision === 0){
            return val;
        }else{
            pow = V.length; //Rember how many powers of ten we need to turn the decimal back to an integer
            V = '0.'+V;
            precision = Math.abs(precision);
            reint = true; //Remeber to change it back
            decp = 1;
        }
    }else if(precision < 0){
        /*
         * Deling with decimal already, but still want to round an intgeger
         * So truncate V and then do the same as above.
         */
        integer = V.slice(0,decp);
        pow = integer.length;
        V = '0.'+integer;
        precision = Math.abs(precision);
        reint = true;
        decp = 1;
    }

    /*
     * Split the integer and decimal parts of the number
     */
    integer = V.slice(0,decp);
    decimal = V.slice(decp+1);

    /** d1 = decimal before the subject decimal **/

    if (decimal.length <= precision){
        //If the precision is less or equal to the number of decimals then we don't need to round
        return val;
    }else if(precision === 0){
        /**
         * Special handling of precision = 0
         * In this case the number before the subject decimal is the last digit of integer
         * not part of the `decimal` variable
         */
        d1 = Number(integer.charAt(integer.length-1));
        integer = integer.slice(0,integer.length-1);//Remove the last digit of integer
    }else{
        d1 = Number(decimal.charAt(precision-1));
    }

    /** d2 = the subject decimal **/
    d2 = Number(decimal.charAt(precision));
    decimal = decimal.slice(0,precision-1); //remove last digit of decimal

    if (mode=='ROUND_CEILING'){
        if (val > 0){
            mode = 'PHP_ROUND_UP';
        }else{
            mode = 'PHP_ROUND_DOWN';
        }
    }else if(mode=='ROUND_FLOOR'){
        if (val > 0){
            mode = 'PHP_ROUND_DOWN';
        }else{
            mode = 'PHP_ROUND_UP';
        }
    }

    switch (mode){
        case 'PHP_ROUND_UP': //Always round up
                d1+=1;
            break;
        case 'PHP_ROUND_HALF_DOWN': //If subject decimal is more than 5 then round up
            if (d2 > 5){
                d1+=1;
            }
            break;
        default: //If the subject decimal is 5 or more, then round up
            //ROUND_HALF_UP
            if (d2 >= 5){
                d1+=1;
            }
            break;
    }

    if(precision === 0){
        /*
         * Again, special handling for precision 0
         * if the round has made a value of 10, then add 1 to the integer and set d1 to 0
         * this works because of the way I concatinate them
         */
        if (d1 == 10){
            integer+=1;
            d1 = '0';
        }
        val=Number(integer+d1);
    }else{
        if (d1 == 10){
            /*
             * intger = 1
             * decimal = 0.555
             * Number(integr+'.'+decimal) = 1.555
             * (0-decimal.length) = -3
             * 1*(10^-3) = 0.001
             * Number(integr+'.'+decimal)+0.001 = 1.556
             */
            val = Number(integer+'.'+decimal)+(1*(Math.pow(10,(0-decimal.length))));
        }else{
            /*
             * otherwsie just re-concatinate the numbers
             */
            val = Number(integer+'.'+decimal+d1);
        }
    }

    if (reint){
        return val*Math.pow(10,pow);
    }else{
        return val;
    }
}

Gravatar
T.Wild
11 Jul '09 Permalink

q  GreenSeed is right, And a test of all 3 digit decimals between 0 and 1 match the PHP value,
A (working) fixed version, not messing with the prototypes:

function round ( val, precision, mode ) {
    // Returns the number rounded to specified precision
    //
    // version: 904.2314
    // discuss at: http://phpjs.org/functions/round
    // +   original by: Philip Peterson
    // +    revised by: Onno Marsman
    // *     example 1: round(1241757, -3);
    // *     returns 1: 1242000
    // *     example 2: round(3.6);
    // *     returns 2: 4
    // Need to support mode flags: PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD

    precision2 = Math.pow(10,precision);
    return Math.round(val*precision2)/precision2;
}

Gravatar
Greenseed
11 Jul '09 Permalink

q  Sorry for last code, was showing what i meaned but wrong :)

here is the working and tested solution.

Number.prototype.round = function(precision)
{
    precision2 = Math.pow(10,precision);
    return Math.round(this*precision2)/precision2;
};



But see this page , into the very bottom , about JS way of storing number

Gravatar
Greenseed
11 Jul '09 Permalink

q  The round funtion will not gave same answer as Php.

PHP:
round(2.835,2) == 2.84

PHP.JS
round(2.835,2) == 2.83

Code i had to add for making it correctely

Number.prototype.round = function(precision) 
{
    var diff = this - this.toFixed(precision);
    return parseFloat( (this+diff).toFixed(precision) );
}


I did not test it very much , but with the value i show seem to work better , so see this as a proof of concept

Gravatar
Kevin van Zonneveld
24 Sep '08 Permalink

q  @ Onno Marsman: works just fine, I've revised it. Muchos! ;)

Gravatar
Onno Marsman
23 Sep '08 Permalink

q  Better than my previous suggestion:

[CODE=&quot;Javascript&quot;]
function round (val, precision) {
return parseFloat(parseFloat(val).toFixed(precision));
}
[/CODE]

Gravatar
Onno Marsman
22 Sep '08 Permalink

q  How about the following?

[CODE=&quot;Javascript&quot;]
function round (val, precision) {
return parseFloat(val).toFixed(precision);
}
[/CODE]

I've checked for a call without precision, it also works fine.


Contribute a New function

More functions

In this category

abs
acos
acosh
asin
asinh
atan
atan2
atanh
base_convert
bindec
ceil
cos
cosh
decbin
dechex
decoct
deg2rad
exp
expm1
floor
fmod
getrandmax
hexdec
hypot
is_finite
is_infinite
is_nan
lcg_value
log
log10
log1p
max
min
mt_getrandmax
mt_rand
octdec
pi
pow
rad2deg
rand
» round
sin
sinh
sqrt
tan
tanh

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: AYHAN BARI*, Nikita Ekshiyan, Nikita Ekshiyan, Petr Pavel, @HalfWinter, Paulo Freitas, Andros Peña Romo, @andorosu, Raimund Szabo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !