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; }
|
|
|
|
|
2023-08-25 15:12:20 +00:00
|
|
|
//public override String ToString() => $"{Value} {Symbol}";
|
|
|
|
public override String ToString() => ToDisplayString();
|
2023-06-27 15:02:56 +00:00
|
|
|
|
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();
|
|
|
|
|
2023-06-27 15:02:56 +00:00
|
|
|
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;
|
2023-06-27 15:02:56 +00:00
|
|
|
|
2023-08-17 06:01:16 +00:00
|
|
|
while (a >= 10000 && i < MaxPrefix)
|
2023-06-27 15:02:56 +00:00
|
|
|
{
|
|
|
|
a /= 1000;
|
|
|
|
i++;
|
|
|
|
}
|
2023-08-17 06:01:16 +00:00
|
|
|
while (a < 10 && i > 0)
|
2023-06-27 15:02:56 +00:00
|
|
|
{
|
|
|
|
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
|
|
|
|
2023-06-27 15:02:56 +00:00
|
|
|
}
|
|
|
|
|