Solved

Display only 2 decimal places

Posted on 2002-03-12
4
148 Views
Last Modified: 2006-11-17
Hi, how can I limit the output of a simple mathematical calculation to 2 decimal places.

eg. answer = 10 * 1.14 / 3.4

In he same breath, where can I find some documentation relating to java's built in math functions...

0
Comment
Question by:psimation
  • 2
4 Comments
 
LVL 30

Accepted Solution

by:
third earned 50 total points
ID: 6856104

  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;
  }


answer = 10 * 1.14 / 3.4;
answer = roundoff(answer,2);


"javascript" math functions,

http://tech.irt.org/articles/js069/

0
 
LVL 30

Expert Comment

by:third
ID: 6856106
sorry should be,

answer = 10 * 1.14 / 3.4;
answer = roundOff(answer,2);
0
 
LVL 46

Expert Comment

by:fritz_the_blank
ID: 6856826
Courtesy of Michel Plungian:

function roundAmount(n) {
  var s = "" + Math.round(n * 100) / 100
  var i = s.indexOf('.')
  if (i < 0) return s + ".00"
  var t = s.substring(0, i + 1) +
     s.substring(i + 1, i + 3)
  if (i + 2 == s.length) t += "0"
  return t
}
0
 
LVL 17

Author Comment

by:psimation
ID: 6858162
Thanks, works like a charm
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now