one unit vs two

Coming from the one country that exclusively uses the imperial system, there’s a lot I take for granted about the way I measure things. In metric, 1.1 kg would make perfect sense, but in the imperial system, 1.1 lbs may look fine but how do you weigh that out. I’m someone with a lot of cooking and baking experience, but I’m not someone for whom mathematical knowledge comes naturally. I know off the top of my head that a pound is 16 ounces, so that’s easy, but what is .1 lbs in ounces. It isn’t quick math, for me anyway. It’s 1.6 oz, but I only know that from googling it. So to deal with this I created a function that converts things like 1.2 lbs to “1 pound 1.6 ounces”

const char **
multiple_units (double amount, GrUnit unit)
{
double amount1 = amount;
double fractional, integer;
const char result[256];

fractional = modf(amount1, &integer);

if (unit != NULL) {
if (fractional > 0)
{
double amount2 = fractional;
GrUnit unit2 = unit;
human_readable(&amount2, &unit2);

if (unit != unit2)
{
amount1 = integer;

char *number1 = gr_number_format(amount1);
char **name1 = gr_unit_get_display_name(unit);
char *number2 = gr_number_format(amount2);
char **name2 = gr_unit_get_display_name(unit2);

snprintf(result, sizeof result, "%s %s, %s %s", number1, name1, number2, name2);
}
else
{
char *number1 = gr_number_format(amount1);
char **name1 = gr_unit_get_display_name(unit);
snprintf(result, sizeof result, "%s %s", number1, name1);
}
}

else
{
char *number1 = gr_number_format(amount1);
char **name1 = gr_unit_get_display_name(unit);

snprintf(result, sizeof result, "%s %s", number1, name1);
}
}

else
{
char *number1 = gr_number_format(amount1);
snprintf(result, sizeof result, "%s", number1);
}

g_message("result is %s", result);

char **result1 = result;

return **result1;
}

Basically it splits the amount into the int and the fractional part of the number, runs the fractional part of the number through my human_readability function which determines whether a unit is the ideal one for human readability (1000000 grams probably makes more sense in terms of kg, etc), if that function changes the unit, the function outputs the int as one unit and the fractional part, now its own int, as a second unit, otherwise it spits out just the amount and the unit as a string, formatted and ready for display.

Leave a Reply

Your email address will not be published. Required fields are marked *