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: ");

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.



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

void setup() {
float x = 100.0;
float y = 7.0;
int i=100*(x/y);

void loop() {}



Try the floor function.

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

void setup() {
  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

max Voltage float is: 1.950000
max Voltage Int is: 195

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.