JavaScript Development
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
 
User Name:
Password:
Remember me
 
Go Back   Dev Articles Community ForumsProgrammingJavaScript Development

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Display Modes
 
Unread Dev Articles Community Forums Sponsor:
  #1  
Old November 1st, 2005, 10:13 AM
smoothdesigner smoothdesigner is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Nov 2005
Posts: 2 smoothdesigner User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 13 m 46 sec
Reputation Power: 0
Question Javascript to Round to 2 Decimal Places?

Hello all,

I have a web form that has an external javascript file attached to it. There is a field called monthlyPremium, which the user will put in their monthly premium (decimals may be needed) and then beside it is a annualPremium field that takes the monthlyPremium data, and multiplies it by 12.

It works fine, unless I put in a value such as 425.65, I get 5107.799999999999 back as the answer, instead of 5107.80. The javascript I have to calculate that is this:

Code:
function fillShenandoah()
    {
		var monthlyPremium = document.weeklyProduction.shenandoahPremium.value
		var months = "12"
		var annualPremium = parseFloat(monthlyPremium * months)

		document.weeklyProduction.shenandoahAnnualPremium.  value = annualPremium

	}


Now, is there a javascript I can put in, to round it to 2 decimal places?

Thanks.

Reply With Quote
  #2  
Old November 1st, 2005, 10:39 AM
MadCowDzz's Avatar
MadCowDzz MadCowDzz is offline
I'm Internet Famous
Dev Articles Frequenter (2500 - 2999 posts)
 
Join Date: Jan 2003
Location: Toronto, Canada
Posts: 2,890 MadCowDzz User rank is Lance Corporal (50 - 100 Reputation Level)MadCowDzz User rank is Lance Corporal (50 - 100 Reputation Level)MadCowDzz User rank is Lance Corporal (50 - 100 Reputation Level) 
Time spent in forums: 1 Week 16 h 19 m 35 sec
Reputation Power: 10
Here's a function that will round to certain decimal points:
Code:
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
Note, num is the number you want rounded and dec is the number of decimal places you want rounded to.

Then use it something like this:
Code:
 var roundedNumber = roundNumber(annualPremium,2)
Comments on this post
smoothdesigner agrees!
colton22 agrees: lol, this looks a lot easier then what i was trying to do!! lol
__________________
Daryl's Homepage | My Blogroll | My Profile | Firefox supporter!
DevArticles Forum Moderator

"The net is a waste of time, and that's exactly what's right about it." -- William Gibson

Reply With Quote
  #3  
Old November 1st, 2005, 10:51 AM
smoothdesigner smoothdesigner is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Nov 2005
Posts: 2 smoothdesigner User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 13 m 46 sec
Reputation Power: 0
Thanks

Thanks.

The code you had on there before you edited worked great.

Code:
var result = Math.round(annualPremium*100)/100


I just set the variable, and then set my document.blah.blah.value = to that, after setting the annualPremium = to the result.

That other code looks great for rounding to different decimal places.

Thanks again

Reply With Quote
  #4  
Old November 1st, 2005, 11:18 AM
MadCowDzz's Avatar
MadCowDzz MadCowDzz is offline
I'm Internet Famous
Dev Articles Frequenter (2500 - 2999 posts)
 
Join Date: Jan 2003
Location: Toronto, Canada
Posts: 2,890 MadCowDzz User rank is Lance Corporal (50 - 100 Reputation Level)MadCowDzz User rank is Lance Corporal (50 - 100 Reputation Level)MadCowDzz User rank is Lance Corporal (50 - 100 Reputation Level) 
Time spent in forums: 1 Week 16 h 19 m 35 sec
Reputation Power: 10
lol, bah... you watched the edits! =P

I modified it to make it a little more global.

Reply With Quote
  #5  
Old September 18th, 2006, 12:49 AM
aleksei aleksei is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Sep 2006
Posts: 1 aleksei User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 16 m 20 sec
Reputation Power: 0
This code does not work

check out thie exampe

Code:
<html>
<head>
</head>

<body>

<script type="text/javascript">

function roundVal(val){
	var dec = 2;
	var result = Math.round(val*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}


var value = 613.305;

document.write(roundVal(value));

</script>

</body>
</html>


The code above produces a result of 613.30 but it should clearly be 613.31

Reply With Quote
  #6  
Old September 18th, 2006, 03:32 PM
colton22's Avatar
colton22 colton22 is offline
\ ^_^ / - *Local Friend*
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2006
Location: near chicago, Illinois
Posts: 475 colton22 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 Days 1 h 36 m 37 sec
Reputation Power: 5
Send a message via AIM to colton22 Send a message via MSN to colton22 Send a message via Yahoo to colton22
Lightbulb i know, i just like work

ill try and create something to round to a certian spot after an input for the digit using strings and substrings with parseing, it shouldnt be that hard but ill go for it.



colton22

Reply With Quote
  #7  
Old October 10th, 2006, 02:59 PM
colton22's Avatar
colton22 colton22 is offline
\ ^_^ / - *Local Friend*
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2006
Location: near chicago, Illinois
Posts: 475 colton22 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 Days 1 h 36 m 37 sec
Reputation Power: 5
Send a message via AIM to colton22 Send a message via MSN to colton22 Send a message via Yahoo to colton22
This is how far i have gotten so far...

Code:
<SCRIPT>
function fixedRound(num2round,digits) {
	var num=num2round.toString();
	if (num.length<=digits) { //>
		var sep=num.indexOf(".");
		if (sep==-1) {num+=".";sep=num.indexOf(".");}
		var dec=num.substring(sep,num.length);
		for (var x=0;x<eval((digits-dec.length)+1);x++)/*>*/{num=num+"0";}
		return num;
	}
	else {
		var sep=num.indexOf(".");
		sep=sep+digits+1;
		num=num.substring(0,sep);
			if (parseInt(num.substring(eval(sep-1),sep))>=5) {movelastnum=true;}else {movelastnum=false;}
			if (movelastnum) {var numbers=new Array();
				for (var x=0;x<num.length;x++)/*>*/{numbers[numbers.length]=num.substring(x,eval(x+1));}
				var long=numbers.length;
				if (numbers[long]!=9) {numbers[long]=numbers[long]+1;}
				else {
					for(var y=long;y>0;y--) {
					if (numbers[y]!=".");
						if (parseInt(numbers[y])==9) {numbers[y]="0";}
						else {numbers[y]=parseInt(numbers[y]);+1;}
					}
					}
			for (var x=0;x<numbers.length;x++) {num+=numbers[x];}}
		return num;
	}
}

alert(fixedRound(prompt("num",""),parseInt(prompt("digits",""))));

</SCRIPT>


if anyone wants to use the above code and run with it go for it.

otherwise i will still be working on it.

colton22

Reply With Quote
  #8  
Old December 12th, 2006, 07:02 AM
thelem thelem is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Dec 2006
Posts: 1 thelem User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 4 m 34 sec
Reputation Power: 0
Quote:
Originally Posted by aleksei
var value = 613.305;
document.write(roundVal(value));

The code above produces a result of 613.30 but it should clearly be 613.31


This is almost certainly a problem with floats. JavaScript cannot store floats precisely, so it 613.305 will probably be stored as something like 613.305000000002, which is correctly rounded up.

The only way to avoid this is to use integers and apply any decimal places at the display stage.

Reply With Quote
  #9  
Old December 13th, 2006, 09:58 AM
colton22's Avatar
colton22 colton22 is offline
\ ^_^ / - *Local Friend*
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2006
Location: near chicago, Illinois
Posts: 475 colton22 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 Days 1 h 36 m 37 sec
Reputation Power: 5
Send a message via AIM to colton22 Send a message via MSN to colton22 Send a message via Yahoo to colton22
alright, i re-did it, i got it to round the example above, but it wont work on like rounding to 0, if anyone wants to critek this alright...

Code:
<SCRIPT>
	function _roundNumber(num,dec) {
		var snum=num.toString()+"000000000000000001";
		var sep=snum.indexOf(".");
		var beg=snum.substring(0,snum.indexOf("."));
		snum=snum.substring(eval(snum.indexOf(".")+1),snum.length);
		var dig=snum.substring(0,eval(dec-1));
		snum=snum.substring(eval(dec-1),dec);
		snum=parseInt(snum);
		gohigher=false;
		if (snum>4) {gohigher=true;}
		if (gohigher) {snum=parseInt(snum);snum++;}
		snum=snum.toString();
		alert(beg+"."+dig+""+snum);
		num=beg+"."+dig+""+snum;
		return num;
	}
alert(_roundNumber(prompt("num"),prompt("number of digits")));
</SCRIPT>


colton22
__________________


Hang Out, Listen To Music, Have Fun, and Customize Your Experiance All In One Place! - Colton22's World - This is My World

Reply With Quote
  #10  
Old April 25th, 2008, 08:08 AM
aspprogrammer aspprogrammer is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Apr 2008
Posts: 1 aspprogrammer User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 25 m 57 sec
Reputation Power: 0
Rounding to 2 decimal places.

Well i tried for it and found it to be quite simple.

myAmt = 234.4243

myAmt.toFixed(2)

The result will be 234.42

Reply With Quote
  #11  
Old October 30th, 2008, 10:22 AM
netshine netshine is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Oct 2008
Posts: 1 netshine User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 10 m 18 sec
Reputation Power: 0
Quote:
Originally Posted by aspprogrammer
Well i tried for it and found it to be quite simple.

myAmt = 234.4243

myAmt.toFixed(2)

The result will be 234.42


.toFixed is NOT reliable! Try it with 0.285, and you will get 0.28 instead of 0.29. The ONLY way to reliably round numbers in Javascript is to parse the number as a string. It is crazy that there is no simple way of doing it, but there you go.

I have written a function to do this, but I am not allowed to post a link to it here because I am a new user! I cannot just paste the code in here either because there is some licensing and contact info that goes with it. So visit netshinesoftware.com and click on the developer blog if you want it!

Reply With Quote
  #12  
Old February 16th, 2009, 01:33 AM
146fhm 146fhm is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Feb 2009
Posts: 1 146fhm User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 4 m 32 sec
Reputation Power: 0
Hmmm, I got It!

Quote:
Originally Posted by netshine
.toFixed is NOT reliable! Try it with 0.285, and you will get 0.28 instead of 0.29. The ONLY way to reliably round numbers in Javascript is to parse the number as a string. It is crazy that there is no simple way of doing it, but there you go.

I have written a function to do this, but I am not allowed to post a link to it here because I am a new user! I cannot just paste the code in here either because there is some licensing and contact info that goes with it. So visit netshinesoftware.com and click on the developer blog if you want it!


Try Using This.....

Code:
function roundNumber(num, dec) {
	var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
	return result;
}

Reply With Quote
  #13  
Old June 2nd, 2009, 06:10 AM
pop pop is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2009
Posts: 1 pop User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 5 m 47 sec
Reputation Power: 0
simple math

There is no specific rule in math that says that .5 should be rounded up to 1.. .5 is just as far from 1 as from 0, therefore it is not a script problem. If you wish to round up by default, then just increase any var ending by .5 slightly.

Reply With Quote
  #14  
Old May 19th, 2010, 01:19 AM
nought nought is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2010
Posts: 1 nought User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 m 15 sec
Reputation Power: 0
round to 2 decimal places.

very old thread I know..... but I like a puzzle (even a very old one).

Code:
function round(n) {
	return Math.round(n*100+((n*1000)%10>4?1:0))/100;
}


test page....

Code:
<html>
<head>
 <script type="text/javascript">
		
	/**
	 * Rounds a number to two decimal places.
	 * 7.335 is rounded to (7.34) so 5/100 always does ceiling)
	 * @n the number to round (float type expected)
	 * @return a rounded number (you may need to pad this to 2 decial places)
	 */
	function round(n) {
		return Math.round(n*100+((n*1000)%10>4?1:0))/100;
	}

	/**
	 * Test harness only. Performs nice decimal padding for us.
	 */
	function tryRound(ctl) {
		var ctl = document.getElementById("txtDummy");
		var val = ctl.value;
		val = parseFloat(val);
		if (!isNaN(val)) {
			var n = round(val)+"";
			if (n.indexOf(".")==-1) {
				n += ".00";
			}
			while(n.length-n.indexOf(".")<3) {
				n += "0";
			}
			ctl.value = n;
		}
	}
 </script>
</head>
<body>
 <form>
  <input id="txtDummy" type="text" value="0"/>
  <a href="#" onclick="tryRound(); return false;">round</a>
 </form>
</html>

Reply With Quote
  #15  
Old June 19th, 2010, 08:52 PM
TheCuriosty TheCuriosty is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2010
Posts: 1 TheCuriosty User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 5 m 28 sec
Reputation Power: 0
Quote:
Originally Posted by pop
There is no specific rule in math that says that .5 should be rounded up to 1.. .5 is just as far from 1 as from 0, therefore it is not a script problem. If you wish to round up by default, then just increase any var ending by .5 slightly.


From what I've learned in math all the way up to university is that in cases where it ends with "5" and you need to round, you round to the nearest EVEN number. So 0.85 = 0.8 and 0.75 = 0.8.

Reply With Quote
Reply

Viewing: Dev Articles Community ForumsProgrammingJavaScript Development > Javascript to Round to 2 Decimal Places?


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump




 Free IT White Papers!
 
Create the Optimal Architecture for your Critical Applications
Warburton's the largest independently owned bakery in the UK faced a number of difficult challenges in providing the most robust yet efficient IT infrastructure for their organization's success. IBM's services combined with their xSeries servers created the perfect platform for their SAP environment with sufficient flexibility, and did so in very time effective fashion.

Request Your Free Technology Downloads!
 
Five Best Practices for Deploying a Successful Service-Oriented Architecture
This white paper describes the benefits you can expect with SOA, and how IBM can help take your business there.

Request Your Free Technology Downloads!
 
Gartner Magic Quadrant for Application Delivery Controllers
Gartner summarizes its view on Application Delivery Controllers, evaluates strengths and weaknesses of solutions, and provides Magic Quadrant reporting for a quick comparison across all vendors. Learn from Gartner how you can benefit from an all-in-one device like Citrix NetScaler that delivers the highest levels of availability, performance and security.

Request Your Free Technology Downloads!
 
Knowledge is Power
What you don't know can hurt you, and is likely costing you money and increasing your security risks during an era of scarce resources. This white paper proposes six key strategies that enterprise security managers can use to improve their network defense posture.

Request Your Free Technology Downloads!
 
Rationalizing the Multi-Tool Environment
The rationalized multi-tool approach is flexible, scalable and cost effective. It provides the necessary input to the IT service management business processes. It preserves prior investments in monitoring tools, empowers technologists to select the best tools with which to do their jobs, and enhances effective response to incidents.

Request Your Free Technology Downloads!
 

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.


© 2003-2010 by Developer Shed. All rights reserved. DS Cluster 12 Hosted by Hostway
For more Enterprise Application Development news, visit eWeek