473,473 Members | 1,569 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Validating float variable in C

beacon
579 Contributor
Hi everybody,

I've just started programming in C and I've run into a problem. The compiler I'm using was distributed by the school and is a piece of work. Something is obviously wrong with it...maybe it's not ANSI compliant or something.

Anyway, I'm trying to figure out if there's a way to read in user input and test to see if it's valid. I'm working with float variables because we're returning currency amounts, but understand that I may have to read the user's input in as a string and then go from there. Problem is, I'm not really sure where to go from there because I don't know if it's possible.

When the value is read in, I need to return a message to the user if the value is incorrect and prompt them to re-enter until they get it right.

Here's my attempt (using pseudocode):
Expand|Select|Wrap|Line Numbers
  1. float amount = 0.0;
  2.  
  3. do{
  4. printf("Please enter an amount: ");
  5. scanf("%f", amount);
  6.  
  7. if (amount != non-numeric character)
  8. return 1;
  9. else
  10. printf("Invalid amount.\n\n");
  11. return 2;
  12. }while(2);
  13.  
Thanks,
beacon
Jan 2 '09 #1
4 8074
Banfa
9,065 Recognized Expert Moderator Expert
If you scanf with %f you will automatically not get any invalid characters. You can not test amount against invalid characters because amount has type float, it is not character based.

So first a couple of best practice guidelines:

With modern computers which have large amounts of memory there is little reason to use float rather than double. Therefore you should not use float in favour of double unless you have a valid and defensible reason to do so.

scanf is a very poor function (especially if used to enter a string using %s) and is best avoided. The function of choice for user input would be fgets which protects against buffer overrun errors.

If working with a fixed point (fixed number of decimal places) then it is often easier and more accurate if using comparisons to use integer types rather than floating point types. For instance in the case of currency assuming you are using $ rather than hold $ as a float hold cents as an integer.


If you really want to using floating point types then for your program I would use fgets to read in the string and then strtod to convert it to a double.

Otherwise I would use fgets to read the string and strtol to convert the various parts of it to cents.
Jan 2 '09 #2
beacon
579 Contributor
Hi Banfa,

Ok, so let me try this again. I'm not sure I completely understand what to do, but I'm going to take my best shot. Btw, it doesn't really matter if I use float or double.

Expand|Select|Wrap|Line Numbers
  1. char strAmount[10];
  2.  
  3. do{
  4. printf("Please enter an amount: "); 
  5. fgets(strAmount, 10, stdin);
  6.  
  7. if((strAmount == 46) || (strAmount < 58 && strAmount > 47)
  8. return 1;
  9. else
  10. printf("Invalid amount.\n\n");
  11. return 2;
  12. }while(2);
  13.  
If I use strtol or strtod, will it return everything if the user enters 49.99? I'm not sure exactly how I would go about converting "the various parts of it to cents."
Jan 2 '09 #3
Banfa
9,065 Recognized Expert Moderator Expert
If it doesn't matter if you use float or double then use double.

Between you fgets and your if you need to convert from a character string to a binary value (either float point or integer type).

strtod would convert all of 49.99 were as when using strtol you would change to call it once to convert the 49, then skip the . and then call it again to convert the 99 then combine the 2 values into a total cents. strtol actually makes this relatively easy and you could easily write a function to take a string of the form nn.mm and produce the result nnmm in an integer (or an error).

That may seem complex however the test amount == 46 will not (or is extremely unlikely) work for floating point types (float, double). This is because a floating point type holds an approximation to a value the chances of it holding 46 even if you entered 46.00 are small.

This is the reason I suggest reading the value in in cents and store it in an integer. Integers do not suffer from the approximation of floating points so the test amount == 4600 (*100 because we are now working in cents) will work for a floating point.
Jan 3 '09 #4
JosAH
11,448 Recognized Expert MVP
@beacon
Ding! You fell for the trap: never, ever use floating point numbers for monetary values; they can't even represent the value of a dime exactly. The first article in this group shows a link about floating format pitfalls; read it.

kind regards,

Jos
Jan 3 '09 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Cristian Tota | last post by:
Hi, I use Visual C++ 6.0. While in debug mode I watch a float variable in the watch window. It has the value -1.#IND0 What does this mean? I haven't found anything about this on the net. ...
3
by: Robb Gilmore | last post by:
Hello, We have a C#.NET app which is calling a Java webservice. We use the wsdl file exportted from the java webservice to create our web-reference in Visual Studio. We are able to create the...
11
by: Joriveek | last post by:
I have a float variable like 123456789 I want to right truncate this and only display say only 8 right most values all the time or otherwise filled by zeros if it is less than 8 digits, do you...
15
by: k3n3dy | last post by:
Hello everybody, I would like to ask anybody to help me understand what should be done exactly with this Problem. I have provided what I have up to now, although it is not quite accurate. Create...
10
by: nas | last post by:
Hi Is there any way that i can find wether float variable contains fraction?? for eg:- if( isWholeNumber(b)) { //do here }
1
by: venu8966 | last post by:
Here is a C pgm, which gives comparison of float variable with its own value, wrong result. main() {float a=0.7; if(a<0.7) printf("it is less"); else printf("it is large"); }
6
by: vlsidesign | last post by:
Newbie question: 0 converted to 0.0 for float variable? If I have the following code, float myTotal; myTotal = 0; will C automatically add a decimal point and at least one zero to the right...
4
by: wangers16 | last post by:
Is it possible to get JavaScript to check the end of the a integer/float variable for a certain number e.g. 5, if so how do you do it? Thanks in advance
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.