post your comment   print   send to a friend
Rate:  50% | Views: 1399
Question categories:  JavaScript

Number rounding in Javascript

Javascript helps lay the foundation for rounding off numbers with the following method:

Math.round (x)

Using this expression, any supplied argument is rounded off to the nearest integer by utilizing the ".5" up rule:

Math.round(25.9) //returns 26
Math.round(25.2) //returns 25
Math.round(-2.58) //returns -3

Let us say you would like to display $25 in standard currency format or PI to infinity. Formatting numbers to specific decimal points utilizes Math.round(), but padded with a little multiplication and division:

var original=28.453

1//round "original" to two decimals
var result=Math.round(original*100)/100 //returns 28.45

2// round "original" to 1 decimal
var result=Math.round(original*10)/10 //returns 28.5

3//round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000 //returns 8.111

The formula to round any number to x decimal points is:

1) Multiple the original number by 10^x (10 to the power of x)
2) Apply Math.round() to the result
3) Divide result by 10^x

Customer Feedback
Rate:  50% | Views: 1399 | Please Rate:  
 
If you have other comments or ideas for future technical tips, please type them here:

Email: (optional)

Comments: (optional)

 Webhosting Service | Register Domain    Back to serch results
Browse the Base
Knowledge Base
Web Design
  Do It Yourself
    JavaScript
Messages
 

Avoid disaster, update your contact e-mail

Avoid disaster , like losing an important domain name, by always keeping your contact e-mail up to date. We send important messages that you don't want to miss. Go to "My account" --> "My info" --> "e-mail" in this Control Panel to update.

Private Area
 
Ask
in Private
   
Personal
Folder
 
Related Questions
 
1. Calculating days remaining until Christmas
 
2. Detecting browser type
 
3. Determining browser type using object detection
 
4. The Internet Explorer challenge
 
5. JavaScript and Forms
 
Home Browse Search Ask in Private Personal Folder   Help
powered by web hosting 
  Logged as: Guest