From 739e87c5ab1afec58d012c797a97553ac281c99c Mon Sep 17 00:00:00 2001 From: chylex Date: Mon, 18 Jul 2022 20:19:38 +0200 Subject: [PATCH] Add one decimal place to MB/GB/TB in the table in the Attachments tab --- app/Desktop/Common/BytesValueConverter.cs | 34 ++++++++++++++--------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/app/Desktop/Common/BytesValueConverter.cs b/app/Desktop/Common/BytesValueConverter.cs index e2b1ea6..66b4685 100644 --- a/app/Desktop/Common/BytesValueConverter.cs +++ b/app/Desktop/Common/BytesValueConverter.cs @@ -4,12 +4,26 @@ using Avalonia.Data.Converters; namespace DHT.Desktop.Common { sealed class BytesValueConverter : IValueConverter { - private static readonly string[] Units = { - "B", - "kB", - "MB", - "GB", - "TB" + private sealed class Unit { + private readonly string label; + private readonly string numberFormat; + + public Unit(string label, int decimalPlaces) { + this.label = label; + this.numberFormat = "{0:n" + decimalPlaces + "}"; + } + + public string Format(double size) { + return string.Format(Program.Culture, numberFormat, size) + " " + label; + } + } + + private static readonly Unit[] Units = { + new ("B", decimalPlaces: 0), + new ("kB", decimalPlaces: 0), + new ("MB", decimalPlaces: 1), + new ("GB", decimalPlaces: 1), + new ("TB", decimalPlaces: 1) }; private const int Scale = 1000; @@ -17,13 +31,7 @@ namespace DHT.Desktop.Common { private static string Convert(ulong size) { int power = size == 0L ? 0 : (int) Math.Log(size, Scale); int unit = power >= Units.Length ? Units.Length - 1 : power; - if (unit == 0) { - return string.Format(Program.Culture, "{0:n0}", size) + " " + Units[unit]; - } - else { - double humanReadableSize = size / Math.Pow(Scale, unit); - return string.Format(Program.Culture, "{0:n0}", humanReadableSize) + " " + Units[unit]; - } + return Units[unit].Format(unit == 0 ? size : size / Math.Pow(Scale, unit)); } public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {