★ wanayoo — archive 1999 http://developer.netscape.com/docs/examples/javascript/rounding.htmlNouvelle recherche | Portail wanayoo



Rounding Off Numbers With JavaScript

You can get greater precision presenting floating point numbers with JavaScript. This is important when dealing with large numbers where precision matters. Here's an example which has a generic function roundOff(). This function can round off long numbers in ways you specify.

Here's the code:

<html>
<head><title>Round off Long numbers</title>
<script>
function roundOff(value, precision)
{
        value = "" + value //convert value to string
        precision = parseInt(precision);

        var whole = "" + Math.round(value * Math.pow(10, precision));

        var decPoint = whole.length - precision;

        if(decPoint != 0)
        {
                result = whole.substring(0, decPoint);
                result += ".";
                result += whole.substring(decPoint, whole.length);
        }
        else
        {
                result = whole;
        }
        return result;
}
</script>
</head>

<body>
<h3><center>Testing Rounding off Long floating point
numbers</center></h3>
<form name=myForm>
<pre>
Enter a long number <input type=text name=text1
value=5.199999999999999999 size=20>
Enter precision     <input type=text name=text2 value=2 size=2>
Result              <input type=text name=text3>
</pre>
<center>
<input type=button value=Calculate onClick="myForm.text3.value =
roundOff(myForm.text1.value, myForm.text2.value)">
</center>
</form>
</body>
</html> 


ADDITIONAL READING
JavaScript Known Bug List
Sample Code Area
Books
Articles
JavaScript Course
Dynamic Style Sheets
Other JavaScript Resources
JavaScript Language Spec
JavaScript Guide
What's New in JavaScript for Navigator 4.0
JavaScript Scripting Tools

VIEW SOURCE ARTICLES

Beyond Data Basics: Writing JavaScript Database Applications, Part 1
Beyond Data Basics: Writing JavaScript Database Applications, Part 2
JavaScript Date Object Techniques
Scripting Layer Effects and Transitions
Detecting a JavaScript Client
Bringing Images to Life with JavaScript

MEMBERS RESOURCES

JavaScript Newsgroup
JavaScript FAQ

For the latest technical information on Sun-Netscape Alliance products, go to: http://developer.iplanet.com

For more Internet development resources, try Netscape TechSearch.


Copyright © 1999 Netscape Communications Corporation.
This site powered by: Netscape Enterprise Server and Netscape Compass Server.