Skip to main content
Version: 2.10.1

Format byte sizes and transfer rates

Orientation

ByteSize keeps a data quantity typed while the application parses, compares, adds, subtracts, and formats it. Numeric extensions create values without manual factors. ByteRate combines a size with a measurement interval for display as bytes, kilobytes, or larger units per second, minute, or hour.

Example

This program parses a size string, performs arithmetic, distinguishes bits from bytes, and formats a transfer rate:

Program.cs
using System.Globalization;
using Humanizer;
using Humanizer.Bytes;
using Humanizer.Localisation;

var culture = CultureInfo.GetCultureInfo("en-US");
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;

var parsed = ByteSize.Parse("1.5 KB");
var combined = parsed + 512.Bytes();
var rate = 3.Megabytes()
.Per(TimeSpan.FromSeconds(2))
.Humanize("0.0", TimeUnit.Second);

AssertEqual(1536d, parsed.Bytes);
AssertEqual("2 KB", combined.Humanize("0", culture));
AssertEqual("1.5 MB/s", rate);
AssertEqual(true, ByteSize.TryParse("12 b", out var bits));
AssertEqual(12L, bits.Bits);

Console.WriteLine("1.5 KB; 2 KB; 1.5 MB/s");

static void AssertEqual<T>(T expected, T actual)
{
if (!EqualityComparer<T>.Default.Equals(expected, actual))
throw new InvalidOperationException($"Expected '{expected}', got '{actual}'.");
}

Create and format sizes

Use Bytes, Kilobytes, Megabytes, Gigabytes, or Terabytes on numeric values, or the corresponding ByteSize.From... factories. Humanize chooses the largest whole unit and accepts ordinary numeric format strings. ToFullWords uses full unit names.

Parse user input

Parse throws for invalid input. In this release, TryParse(string, IFormatProvider, out ByteSize) accepts an explicit provider and returns false without throwing. Span overloads are later additions.

Calculate rates

Call size.Per(interval).Humanize(format, TimeUnit.Second). Rate display supports second, minute, and hour units but has no culture parameter in this release.

Pitfall

Humanizer’s KB, MB, GB, and TB values use binary multiples of 1024. They are not SI decimal units. The symbols b and B are intentionally case-sensitive: lowercase is bits, uppercase is bytes. Other recognized unit suffixes are case-insensitive. Fractional bits and values without a unit suffix are invalid.

Construct rates with a positive, nonzero interval. Keep ByteSize as the model value; formatted output is not a serialization contract.

Version notes

ByteSize and ByteRate live in Humanizer.Bytes in this 2.x release. Culture-aware ByteRate.Humanize and span parsing are unavailable; string parsing with an explicit provider is available.