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 5556 57 58 59 6061 62 63 64 6566 67 68 69 7071 72 73 74 7576 77 78 79 8081 82 83 84 8586 87 88 89 9091 92 93 94 9596 97 98 99 100101 102 103 104 105106 107 108 109 110111 112 113 114 115116 117 118 119 120121 122 123 124 125126 127 128 129 130131 132 133 134 135136 137 138 139 140141 142 143 144 145146 147 148 149 150151 152 153 154 155156 157 158 159 160161 162 163 164 165166 167 168 169 170171 172 173 174 175176 177 178 179 180181 182 183 184 185186 187 188 189 190191 192 193 194 195196 197 198 199 200201 202 203 204 205206 207 208 209 210211 212 213 214 215216 217 218 219 220221 222 223 224 225226 227 228 229 230231 232 233 234 235 | function round (val, precision, mode) { // Returns the number rounded to specified precision // // version: 1008.1718 // 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) // % 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(1.17499999999999, 2); // * returns 5: 1.18 /* Declare Variables * retVal - Temporary holder of the value to be returned * V - String representation of val * integer - Integer portion of val * decimal - decimal portion of val * decp - Character index 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) { // round to odd or even if (even === true) { if (dtLa === 50) { if ((dtR % 2) === 1) { if (dtLa >= 5) { dtR++; } else { dtR--; } } } else if (dtLa >= 5) { dtR++; } } else { if (dtLa === 5) { if ((dtR % 2) === 0) { if (dtLa >= 5) { dtR++; } else { dtR--; } } } else if (dtLa >= 5) { dtR++; } } return dtR; }; var _round_half_ud = function (dtR, dtLa, up) { // round up or down if (up === true) { if (dtLa >= 5) { dtR++; } } else { if (dtLa > 5) { dtR++; } } 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 integers *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 - Integer protion of Val *decimal - Decimal portion of Val *DigitToRound - The digit to round *DigitToLookAt- The digit to compare 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; // Fall-through case 'down': round = _round_half_ud; break; case 'even': bool = true; // Fall-through 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 { // 0 decimal places 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((Number(integer) + 1) + decimal); // Need to add extra 0 since passing 10 } 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'; } negative = val < 0; // Remember if val is negative 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 decimal 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 integer=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; } if (decimal === '0') { return Number(integer); } val = Number(integer + '.' + decimal); // After sanitizing, recreate val } // Call approriate function based on passed mode, fall through for integer constants 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; } return negative ? 0 - retVal : retVal; } |
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.
@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...
@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! :)
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);
}
@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...
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);
}
@ 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?
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.
@ T.Wild: Great job!
(for the record: I like http://phpjs.org/functions/pathinfo:486 's way of handling constant arguments best)
@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.
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]
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.
@ 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.
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.
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;
}
}
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;
}
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
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


Josep Sanz
Sep 2nd
I detect an error:
If I change the precision to 1 or 3, work as expected
Thanks.