quick question convert int to float

I have an int variable, how can I convert it to a float? Right now I have:

int ledRowNumber;
float ledRowNumberFloat;

and I tried:

ledRowNumberFloat = ledRowNumber*1.0;

I'm not sure if it's working. Should this work?

I would guess so. Are you seeing something that shows it is not?

Yes. You could also just do

ledRowNumberFloat = ledRowNumber

or (Better practice)

ledRowNumberFloat = (float)ledRowNumber

To convert! :slight_smile:

I agree with Fuzzyzilla that both will work. I, too, prefer the second version which performs an explicit cast to float. I prefer it because it more clearly documents your intent.

perigalacticon:
I'm not sure if it's working. Should this work?

Do you have any reason to believe it's not working?

I thought it wasn't working but it's part of a debugging process so it was hard to tell initially. It works great now thanks!

In general, basic, core parts of the C++ programming language don't simply "not work". If they did, no-one's code would run at all.

PaulMurrayCbr:
In general, basic, core parts of the C++ programming language don’t simply “not work”. If they did, no-one’s code would run at all.

That’s quite a thing to say. There have been many times that I have written something that I thought was totally correct, but didn’t work as expected because I didn’t know about some arcane syntax rule. Proper debugging requires the humble ability to doubt everything that you have written.

If you dispute this, remind yourself how many people you’ve seen complaining about why their delays aren’t the right length when they try to multiple 10 * 60 * 1000 (integer truncation). Or why they keep getting 0 when they do float result = analogRead(0) / 1024 * 5 (integer division). You have as many posts as I do, I’m sure you’ve seen many.

Against this backdrop, if there is some bug in code related to this snippet I think it’s perfectly reasonable for perigalacticon to doubt whether or not he is performing the conversion properly. The fact that it wasn’t the problem doesn’t mean it was wrong to think it was a possibility.

perigalacticon:
I have an int variable, how can I convert it to a float? Right now I have:

int ledRowNumber;
float ledRowNumberFloat;

and I tried:

ledRowNumberFloat = ledRowNumber*1.0;

I'm not sure if it's working. Should this work?

Yes. And even RowNumberFloat = ledRowNumber; should work.

(Implicit type conversion in C/C++)

@perigalacticon: For some additional details on casts in C, read #1 here.