2

I'm have this assignment where you have to get an input of type float from the user which represents a value in dollars for example

4.05

so I want to convert this float to an int such that it becomes in cents so the value of the int should be 405 , I need to do this in C, anyone can provide some help ?

3 Answers3

3

Since this is homework, here are some leading questions:

  1. You need to change a number in dollars to cents. What mathematical operation would do that?
  2. You need to convert the result of that mathematical operation to an integer. How can you convert a float to an integer? (Hint: casting)
Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
  • Casting is going to get him off by a penny. I suppose that's what the homework assignment is about. (Hint: rounding) – Hans Passant Aug 15 '11 at 23:06
0

First result on google with "float to int c": http://www.cs.tut.fi/~jkorpela/round.html. Next time, please google it !

ldiqual
  • 15,015
  • 6
  • 52
  • 90
  • This truncates whats after the floating point -_- , thats exactly what I don't want to do –  Aug 15 '11 at 22:32
  • @aedes993 I think he assumed you know how to convert from dollars to cents before converting to int. Too high an assumption? – Christian Rau Aug 15 '11 at 22:38
  • @aedes993 As this is homework no one's going to just answer it; you have to convert the dollars to cent first by simple maths and then cast it – Will03uk Aug 15 '11 at 22:46
0

This is sort of incidental to your question but in case you should decide to go further with your programming career and want to code something that involves non-integer values of money, you're safest using some kind of decimal floating point library to avoid precision errors.

This is for Python but explains the rationale for using proper decimal numbers with currencies:

http://docs.python.org/library/decimal.html

In this assignment you'll probably be fine without it but using it and/or bringing it up in class might win a few extra credit points with your teacher. ;)

Kristoff vdH
  • 224
  • 2
  • 4