n4rzul n4rzul - 3 years ago 134
C# Question

c# unit conversion library for food amounts

I want to implement a simple unit conversion library for food measurements, ie cups teaspoons. pinch, milliliters, ounces, liters, grams, pounds etc etc etc.
Are there any libraries out there that I can use allready, if not I want to roll my own in the pseudo manner below:

enum Unit
{
Centimeters = 0,
Meter = 1,
Kilometer = 2
}


//| | | 0 | 1 | 2 |
//----------------------------------------------
//| | |Centimeters| Meters| Kilometers|
//----------------------------------------------
//|0|Centimeters|1 | 0.01 | 0.000001 |
//----------------------------------------------
//|1|Meters |100 | 1 | 1000 |
//----------------------------------------------
//|2|Kilometers |100000 | 1000 | 1 |
//----------------------------------------------


public float Convert(Unit UnitFrom, Unit UnitTo, UnitValue)
{
float factor = UnitMatrix[UnitFrom][Unit UnitTo];
return UnitValue * factor;
}

//Usage
Convert(Unit.Kilometers, Unit.Meters, 5)
// Lookup factor in this case would be the one at [2, 1] i.e. 1000 so output is 5000


Pointers, pitfalls, too naive? Any help would be useful.
A current opensource implementation that I can study would be great too.
TIA

Answer Source

@n4rzul, I have started developing an open-source units-of-measurement library in C#, that could easily be extended with any unit of your request. Please have a look at the project website at Github, https://github.com/cureos/csunits, and see if this library meets your needs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download