Innovenergy_trunk/csharp/Lib/Units/Unit.cs

49 lines
1.2 KiB
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 override String ToString() => ToDisplayString();
2023-08-18 13:57:00 +00:00
private static readonly IReadOnlyList<String> Prefix = new[] { "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Y" };
private static Int32 MaxPrefix { get; } = Prefix.Count - 1;
private static Int32 DefaultIndex { get; } = Prefix.TakeWhile(e => e != "").Count();
public String ToDisplayString()
{
if (Value == 0)
return $"0 {Symbol}";
var a = Math.Abs(Value);
var s = Math.Sign(Value);
2023-08-18 13:57:00 +00:00
var i = DefaultIndex;
while (a >= 10000 && i < MaxPrefix)
{
a /= 1000;
i++;
}
while (a < 10 && i > 0)
{
a *= 1000;
i--;
}
var r = a < 100
? Math.Floor(a * 10) / 10
: Math.Floor(a);
return $"{r * s} {Prefix[i]}{Symbol}";
}
2023-08-18 13:57:00 +00:00
}