954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Small problem but cant find help anywhere.... pls help

consider this:

float a=3.145698,b;

que: now how can I assign b=3.14 using 'a' instead of 3.145698.

pls help me... thank you very much....

hardikvd
Newbie Poster
4 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 
float a=3.145698;
float b=a;

define b as a; if you only want 3.14, just set the float precision to 2.

SeeTheLite
Junior Poster
109 posts since Mar 2009
Reputation Points: 38
Solved Threads: 13
 
float a=3.145698;
float b=a;

define b as a; if you only want 3.14, just set the float precision to 2.


thnk u friend for taking interest in this prob.. but would you pls tell me the exact syntax to set the float precision to 2....

hardikvd
Newbie Poster
4 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

thnk u friend for taking interest in this prob.. but would you pls tell me the exact syntax to set the float precision to 2....

hardikvd
Newbie Poster
4 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

cout << fixed << setprecision(2) << b ;

This will keep it to 2 decimal places.

Now i have a problem !! when you do that it will round off the values to about 3.15,i had a similar problem earlier to which i have not yet found a solution.

How do you make sure it does not round off the value,in my case the value was 0.003974 , how do i get only 0.003 ?

dchunt
Newbie Poster
19 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Er I should have been more clear, there is something besides setprecision() that allows you to "cut off" anything after a certain digit. Google it; you have to learn something on your own :P. I don't like giving away freebies; it takes away the fun in learning.

SeeTheLite
Junior Poster
109 posts since Mar 2009
Reputation Points: 38
Solved Threads: 13
 

I know how to print upto 2 decimal points.. but i want to know how can I assign the value to float variable b=3.14 using a=3.1469532...
pls send the solution with syntax... thnx

hardikvd
Newbie Poster
4 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

If you want to store 3.14 (and no more), then you need a different data type than a float.

You're always going to end up with either 3.139999999 or 3.140000001, depending on which is the nearest representable form to the value 3.14

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

Its simple as this

float a = 3.1234567;
float b = int (a * 1000 ) / 1000.0f  // now b = 3.123
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You