0

There is integer variable, voltage in millivolts.

signed int voltage_mv = 134; //134mV

I have 2-segment display and I want to display hundredths of volts.

How can I convert milivolts to hundredths volts in one operation? Without IF statement, without function?

134 => 13
135 => 14
Meloun
  • 13,601
  • 17
  • 64
  • 93

2 Answers2

9

How about simple rounding:

int millivoltToDisplay (int millivolts)
{
  return (millivolts+5)/10;
}

(written as a function for clarity)

Nils Pipenbrinck
  • 83,631
  • 31
  • 151
  • 221
  • 6
    What if the input value is negative ? For correct rounding you need to test for this and subtract 5 rather than add 5, i.e. `return mv >= 0 ? (mv + 5) / 10 : (mv - 5) / 10;` – Paul R Nov 03 '10 at 08:45
  • to Paul R. - great, thats it! – Meloun Nov 03 '10 at 08:59
4

For the same of completeness, if the denominator is odd, then instead of doing:

return (millivolts+denominator/2)/denominator;

you can just have

return (2*millivolts+denominator)/(2*denominator);

and get the correct rounding.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jean-Marc Valin
  • 302
  • 1
  • 2