Innovenergy_trunk/csharp/Lib/Units/Unit.cs

43 lines
914 B
C#
Raw Normal View History

2023-06-13 11:03:49 +00:00
namespace InnovEnergy.Lib.Units;
public abstract class Unit
{
protected Unit(Double value) => Value = value;
public abstract String Symbol { get; }
public Double Value { get; }
public override String ToString() => $"{Value} {Symbol}";
public String ToDisplayString()
{
if (Value == 0)
return $"0 {Symbol}";
var a = Math.Abs(Value);
var s = Math.Sign(Value);
var i = 8;
while (a >= 10000)
{
a /= 1000;
i++;
}
while (a < 10)
{
a *= 1000;
i--;
}
var r = a < 100
? Math.Floor(a * 10) / 10
: Math.Floor(a);
return $"{r * s} {Prefix[i]}{Symbol}";
}
private static readonly IReadOnlyList<String> Prefix = new[] { "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Y" };
}