428,759 Members | 1,778 Online
Need help? Post your question and get tips & solutions from a community of 428,759 IT Pros & Developers. It's quick & easy.

# Rounding a number(from advice given here)

 P: n/a From previous postings, I assume that the round method of the Math object leaves too much to chance, and should not be used. It has also been suggested that rounding be done by converting the number to string - then use string manipulation. So - with that in mind, please check the validity of the following code: // the args: n is the number to round, and x the number of places function roundNtoXplaces(n, x){ // move the decimal over x places n = n * (Math.pow(10, x)); // coerce the number to a string n = "" + n; // split the string at the new decimal place var numParts = n.split("."); // if the decimal part would come after "5" if sorted alphabetically, // then add 1 to the int part if (numParts[1]+"" >= "5"){ numParts[0]++; } //coerce the number back to a string // This string contains the numbers we will be returning numParts[0] += ""; //get the length of the string var len = numParts[0].length; // since we moved the decimal over to work with it, now we put it back // intPart is the part before the decimal var intPart = numParts[0].substr(0, (len - x)); //decimalPart is the part of the string after the decimal var decimalPart = numParts[0].substr( len - x, x ); var outString =intPart + "." + decimalPart; return outString; Apr 7 '06 #1
6 Replies

 P: n/a > return outString; I left off the closing "}" curly-braces when pasting the code. And of course I know the number of lines can be condensed and the code could be obfusicated beyond recognition. The extra steps and comments are there for clarity. Apr 7 '06 #2

 P: n/a JRS: In article , dated Fri, 7 Apr 2006 14:12:11 remote, seen in news:comp.lang.javascript, Hal Rosser posted :From previous postings, I assume that the round method of the Math objectleaves too much to chance, and should not be used. It has also beensuggested that rounding be done by converting the number to string - thenuse string manipulation. To show potential intelligence, you could have refrained from starting a new thread and you could have indented your code, as is customary, to show structure. You could also have tested it. So - with that in mind, please check the validity of the following code:// the args: n is the number to round, and x the number of placesfunction roundNtoXplaces(n, x){// move the decimal over x placesn = n * (Math.pow(10, x));// coerce the number to a stringn = "" + n;// split the string at the new decimal placevar numParts = n.split(".");// if the decimal part would come after "5" if sorted alphabetically,// then add 1 to the int partif (numParts[1]+"" >= "5"){numParts[0]++;} To test whether the first character of a string is 5 or more, knowing that it will be in 0..9, one might use S.charAt()>="5" - it seems OK with an empty string - undertested. //coerce the number back to a string// This string contains the numbers we will be returningnumParts[0] += "";//get the length of the stringvar len = numParts[0].length;// since we moved the decimal over to work with it, now we put it back// intPart is the part before the decimalvar intPart = numParts[0].substr(0, (len - x));//decimalPart is the part of the string after the decimalvar decimalPart = numParts[0].substr( len - x, x );var outString =intPart + "." + decimalPart;return outString; Missing } shows carelessness. roundNtoXplaces(0.0, 2) .1 roundNtoXplaces(0.07, 2) .7 roundNtoXplaces(90.07, 2) 90.08 roundNtoXplaces(-90.07, 2) -90.06 roundNtoXplaces(0.0999, 2) .10 ** roundNtoXplaces(11.34, 5) 11.34001 ** Numerically correct but format deprecated. -- © John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 © JL/RC: FAQ of news:comp.lang.javascript jscr maths, dates, sources. TP/BP/Delphi/jscr/&c, FAQ items, links. Apr 7 '06 #3

 P: n/a > To show potential intelligence, you could have refrained from starting a new thread and you could have indented your code, as is customary, to show structure. *** OK ** but potential intelligence may be too fleeting for me You could also have tested it. *** I did, but you did a much better job at that. To test whether the first character of a string is 5 or more, knowing that it will be in 0..9, one might use S.charAt()>="5" - it seems OK with an empty string - undertested. *** I wanted to see if the string, if sorted alphabetically, would come on or after a "5. Missing } shows carelessness. *** yeah, When I copied it from the web page I tested it on, the "}" didn't make the copy buffer. I inadvertantly left it off. **** Thanks for taking the time to test the code. The bad output examples you pointed out helped a lot in debugging. The revised code fixes those errors, and I also tested the function with ramdom numbers and random 'places', and seems to be working now. (I wrote a function to test it 100 times and it looks ok.) (I don't know what it was about ".07", but adding zeroes to the end of the string fixed that part. I think an empty string must be rounding to 1.) ** ***** Here's the revised code ** // the args: n is the number to round, and x the number of places // This function formats to x decimal places - padding with trailing // zeroes if required function roundNtoXplaces(n, x){ var itWasNegative = false; if (n < 0){ n*=-1; itWasNegative = true; } // move the decimal over x places n = n * (Math.pow(10, x)); // coerce the number to a string n = "0" + n; //** to assure there is something after the deci9mal to work with if (n.indexOf(".") < 0){ n += ".0000" } // split the string at the new decimal place var numParts = n.split("."); //** to avoid empty array, add zeroes to the end of the string*** numParts[1] += "" + "00000"; // if the decimal part would come after "5" if sorted // then add 1 to the int part if (numParts[1]+"" >= "5"){ numParts[0]++; } // coerce the number back to a string // This string contains the numbers we will be returning numParts[0] = "" + numParts[0]; //get the length of the string var len = numParts[0].length; // since we moved the decimal over , now we put itback // intPart is the part before the decimal var intPart = numParts[0].substr(0, (len - x)); intPart *=1; // removes leading zeroes //decimalPart is the part of the string after the decimal var decimalPart = numParts[0].substr( len - x, x ); if (itWasNegative){ intPart *=-1; } var outString = intPart + "." + decimalPart; return outString; }// Here's that pesky closing curly-brace ;-) Apr 8 '06 #4

 P: n/a JRS: In article , dated Fri, 7 Apr 2006 21:36:55 remote, seen in news:comp.lang.javascript, Hal Rosser posted : To show potential intelligence, you could have refrained from starting a new thread and you could have indented your code, as is customary, to show structure.*** OK ** but potential intelligence may be too fleeting for me Duplicating News in Mail is quite unnecessary. Doing do without explicit wanting in both media is extremely bad manners. -- © John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME © Web -> Timo Salmi: Usenet Q&A. Web : about usage of News. No Encoding. Quotes before replies. Snip well. Write clearly. Don't Mail News. Apr 8 '06 #5

 P: n/a "Dr John Stockton" wrote in message news:k4**************@merlyn.demon.co.uk... JRS: In article , dated Fri, 7 Apr 2006 21:36:55 remote, seen in news:comp.lang.javascript, Hal Rosser posted : To show potential intelligence, you could have refrained from starting a new thread and you could have indented your code, as is customary, to show structure.*** OK ** but potential intelligence may be too fleeting for me Duplicating News in Mail is quite unnecessary. Doing do without explicit wanting in both media is extremely bad manners. My apologies. Calling folks stupid is ok, but not an inadvertant mouse click? I carelessly but unintentionally clicked "reply" instead of "reply group". The message was returned undeliverable, anyway. Get back to work. :-) Apr 9 '06 #6

 P: n/a "Dr John Stockton" kirjoitti viestissä news:k4**************@merlyn.demon.co.uk... JRS: In article , dated Fri, 7 Apr 2006 21:36:55 remote, seen in news:comp.lang.javascript, Hal Rosser posted : To show potential intelligence, you could have refrained from starting a new thread and you could have indented your code, as is customary, to show structure.*** OK ** but potential intelligence may be too fleeting for me Duplicating News in Mail is quite unnecessary. Doing do without explicit wanting in both media is extremely bad manners. Thank you for teaching gad manners for us. : Apr 10 '06 #7

### This discussion thread is closed

Replies have been disabled for this discussion.