Patch to fix rounding error with CPU values.
[monky] / src / temphelper.c
1 /* temphelper.c:  aid in converting temperature units
2  *
3  * Copyright (C) 2008 Phil Sutter <Phil@nwl.cc>
4  *
5  * This library is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
18  * USA.
19  *
20  */
21 #include "config.h"
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <ctype.h>
26 #include <sys/types.h>
27 #include "temphelper.h"
28 #include "conky.h"
29
30 /* default to output in celsius */
31 static enum TEMP_UNIT output_unit = TEMP_CELSIUS;
32
33 static double
34 fahrenheit_to_celsius(double n)
35 {
36         return ((n - 32) * 5 / 9);
37 }
38
39 static double
40 celsius_to_fahrenheit(double n)
41 {
42         return ((n * 9 / 5) + 32);
43 }
44
45 int
46 set_temp_output_unit(const char *name)
47 {
48         size_t i;
49         int rc = 0;
50         char *buf;
51
52         if (!name)
53                 return 1;
54
55         buf = strdup(name);
56         for (i = 0; i < strlen(name); i++)
57                 buf[i] = tolower(name[i]);
58
59         if (!strcmp(buf, "celsius"))
60                 output_unit = TEMP_CELSIUS;
61         else if (!strcmp(buf, "fahrenheit"))
62                 output_unit = TEMP_FAHRENHEIT;
63         else
64                 rc = 1;
65         free(buf);
66         return rc;
67 }
68
69 static double
70 convert_temp_output(double n, enum TEMP_UNIT input_unit)
71 {
72         if (input_unit == output_unit)
73                 return n;
74
75         switch(output_unit) {
76                 case TEMP_CELSIUS:
77                         return fahrenheit_to_celsius(n);
78                 case TEMP_FAHRENHEIT:
79                         return celsius_to_fahrenheit(n);
80         }
81         /* NOT REACHED */
82         return 0.0;
83 }
84
85 int temp_print(char *p, size_t p_max_size, double n, enum TEMP_UNIT input_unit)
86 {
87         int out;
88         size_t plen;
89
90         out = round_to_int_temp(convert_temp_output(n, input_unit));
91         plen = spaced_print(p, p_max_size, "%d", 3, out);
92
93         return !(plen >= p_max_size);
94 }