Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C (http://www.programmingforums.org/forum60.html)
-   -   set a number to 2 digits only (http://www.programmingforums.org/showthread.php?t=10639)

hipolito Jul 6th, 2006 8:12 AM

set a number to 2 digits only
 
Hi, I have some numbers in float format, such as

87,990001

and I want to set it to 87,99.
Can I still use float?
how do I do it?

thx

thondal Jul 6th, 2006 8:20 AM

I'm at work now and relativly new at C, but I can almost remember the answer to this one. You can still use float, but at some point you have to declare how many numbers it is supposed to show after the , or as a whole. If noboy answers this within the next 4 hours I might be able to get home and find out how.

-thondal-

hipolito Jul 6th, 2006 8:22 AM

Thx thondal

thondal Jul 6th, 2006 8:28 AM

By the way, if you have the oppertunity to go to a library you can go down and borrow/read the "C for dummies" book. The answer should be in it, somwhere between chapter 7 and 14 or something.

hipolito Jul 6th, 2006 8:31 AM

yeah, I know, I can do that, but Im at work right now and cant fo there. What I do need also is how to start another C program from a C.

Ooble Jul 6th, 2006 8:39 AM

To use printf to output floating-point numbers to a certain number of decimal places:
:

float number = 87.99237;
printf("%.2f", number);
// prints: "87.99"
printf("%.4f", number);
// prints: "87.9924"
printf("%.0f", number);
// prints: "88"


thondal Jul 6th, 2006 8:42 AM

aah, Ooble to the rescue ;)

-thondal-

hipolito Jul 6th, 2006 8:45 AM

Well, thx for that, but I need to use the number in the program, not as an output. I will compare the float number with 2 digits with other numbers.

Narue Jul 6th, 2006 8:47 AM

>and I want to set it to 87,99.
>Can I still use float?
Rule #1 about numbers: The value and how you represent the value are different. If you have 87,990001 in memory, it's always going to be 87,990001, regardless of how you represent it. Well, that's not actually true. The number will be a string of bits that always has the same pattern, and how you choose to represent that pattern will change. 87,990001 is in reality, already a representation of the value, not the actual value except in an abstract sense.

>how do I do it?
printf and friends are ideal for this:
:

printf ( "%.2f\n", my_float );

thondal Jul 6th, 2006 8:50 AM

But as he says he needs to use it in the program not as a output, is it not possible at the beginning when you make the my_float to also define how many number my_float is supposed to store? I.e my_float=[4] or something?


-thondal-


All times are GMT -5. The time now is 12:52 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC