# Convert float to Int

I have a variable called maxVoltage, say maxVoltage = 1.95. How can i convert this to 195, in essence i want to "remove" the decimal point.

If i multiply by 100

int maxVoltageInt = maxVoltage * 100;

Serial.print("max Volage is now: ");
Serial.println(maxVoltageInt);

I get 196 in the output

What you are doing is correct.

Serial.print() rounds off to the specified decimal place (default 2), and float values are generally not exact, so you can accept the value 196.

However, if you just want to print the "1" of "1.95" use Serial.print(maxVoltage,0)

so you can accept the value 196.

I could, but i don't want that I need to essential "remove" the decimal point.

1.25 becomes 125, 1.98 becomes 198 etc.

Have you tried

int maxVoltageInt = maxVoltage * 100.0;

No idea whether it will make much dfference.

try

Serial.println(maxVoltageInt,0);

Float values are not exact. To see the problem, this:

void setup() {
Serial.begin(9600);
float x = 100.0;
float y = 7.0;
Serial.println(x/y,0);
Serial.println(x/y);
Serial.println(x/y,4);
int i=100*(x/y);
Serial.println(i);
}

void loop() {}

Prints:

14
14.29
14.2857
1428

Try the floor function.

Hum... are yous sure? I don't get 196. Just tried this

void setup() {
Serial.begin(115200);
float maxVoltage = 1.95;
int maxVoltageInt = maxVoltage * 100;
Serial.print("max Voltage float is: "); Serial.println(maxVoltage, 6); // with 6 digits
Serial.print("max Voltage Int is: "); Serial.println(maxVoltageInt);
}

void loop() {}

Serial Monitor (@ 115200 bauds) shows

[color=purple]
max Voltage float is: 1.950000
max Voltage Int is: 195
[/color]

This might be the case where you are measuring voltage from an analog pin converting to actual volts using floats . If stick with integer arithmetic , say working in millivolts, rather than volts you won’t get an issue.

In your case you’ve 2950 millivolts , if you need to display as volts , just hard code a decimal point in the right place .

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.