Thank you for being a valued part of the CNET community. As of December 1, 2020, the forums are in read-only format. In early 2021, CNET Forums will no longer be available. We are grateful for the participation and advice you have provided to one another over the years.

Thanks,

CNET Support

General discussion

Javascript round function

Apr 12, 2006 2:04AM PDT

hey i am working on a simple javascript html assignment and i am trying to get my numbers to round and i cant.

they way the function works, the user inputs 2 numbers and then it multiplies those numbers, but i need the output number to be only to 2 decimal places.

http://web.bentley.edu/students/l/lokhand_aadi/tipcalculator.html

here's the link to the actual site. any help i would appreciate.

Discussion is locked

- Collapse -
LINK ONLY.
Apr 12, 2006 2:24AM PDT
- Collapse -
enhanced Math.round()
Apr 13, 2006 4:18AM PDT

Here's code that enhances the standard function. Use it just like the standard function, but pass the decimal precision as the second argument. If the precision is omitted, it acts just like the standard function.

Math._round = Math.round;
Math.round = function( num , dec )
{
if (typeof(dec) == "undefined") dec = 0; else dec = Math.floor( dec );
if (isNaN(num + dec) || dec < 0 || dec > 12) return Math._round( num );
var n = Math.pow( 10, dec );
return Math._round( num * n ) / n;
}


alert( Math.round( 10 / 3, 2 ) )

- Collapse -
Very nice, but ...
Apr 14, 2006 4:29AM PDT

it's one of the unwritten rules in these forums we never do the homework for students. They learn more if they find out themselves.

From that point of few it's better to give a hint only.
Something like: to round to three decimal places, multiply by 1000, round to integer and divide the result by 1000. That leaves it to them to find out the javascript involved, and that's the purpose of the assignment.

I'm a parttime teacher myself, so I got to note this.

Kees

- Collapse -
sorry
Apr 15, 2006 6:02AM PDT

i didn't realize it was a student (i guess "assignment" and ".edu" should have tipped me off). i just know how frustrating js can be since so much common functionality (trim string, date formatting, number formatting, etc.) was omitted or is somewhat veiled. at least i didn't tell 'em how to format the number to #.##!

- Collapse -
simple solution to round off numbers to 'x' places decima
Mar 25, 2008 11:45PM PDT

var num = 15.56789342;
var result = num.toFixed(2);

result = 15.56

- Collapse -
That's not rounding. That's truncating.
Mar 26, 2008 6:00AM PDT

Rounding would give 15.57.

Kees