3

I am building an app that displays how many miles you have gone and I want it to have 3 decimal places. So "0.435 miles" for instance. I have tried the code below:

static char stopwatch_miles[50];
snprintf(stopwatch_miles, sizeof(stopwatch_miles), "%.3f miles", num_miles);
text_layer_set_text(miles_layer, stopwatch_miles);

num_miles is a calculated floating point variable. However, Pebble deprecated using floats in snprintf in 1.13. Is there an easy workaround? Maybe using an int, multiplying it by 1000 before my math and adding the decimal places in formatting?

nobody
  • 19,814
  • 17
  • 56
  • 77
Jaret Burkett
  • 123
  • 2
  • 7

1 Answers1

4

You could try multiply 'num_miles' by 1000, convert it to an integer, and them display as a regular int value

snprintf(stopwatch_miles, sizeof(int), "%d.%d miles", (int)num_miles, (int)(num_miles*1000)%1000);

EDIT: Manül gently reminded me that the second %d should be %03d instead of the former answer. The line should then be:

    snprintf(stopwatch_miles, sizeof(stopwatch_miles), "%d.%03d miles", (int)num_miles, (int)(num_miles*1000)%1000);
Yamaguti
  • 146
  • 4
  • 3
    the second %d should be %03d to handle for example 0.043 miles – mch Jun 12 '14 at 15:41
  • I could not get this to function properly. What I got to work is doing the exact same thing in a different function, using 2 ints, one for before period, and one for after, and doing the whole thing as an int instead of a float. Thank you for pointing me in the right direction. – Jaret Burkett Jun 12 '14 at 16:22
  • 2
    `sizeof(int)` is wrong here. It needs to be the size of `stopwatch_miles` – nobody Jun 12 '14 at 16:58
  • @JaretBurkett, that is exactly what the code above is supposed to do. – Yamaguti Jun 13 '14 at 19:01