Make .Net Data Types Human Readable with Humanizer

Humanizer is a nice library to get human readable representations for strings, numbers and dates in .Net. Cutting strings down to a certain size or turning a TimeSpan into “an hour” isn’t magic. Nevertheless, trying to do all that work on your own will take time that Humanizer has already spent. Let’s look on a few use cases where this library has proven to be a great help.

 

Installation

Open your project in the Solution Explorer in Visual Studio, right-click on References and select “Manage NuGet Packages…” to open the NuGet packages dialog. Search for Humanizer and install this package:

 

A few minutes ago from a DateTime

Many sites offer you that nice feature where they show you how long ago a comment was written. Depending on the duration, you get an understandable unit (“a few minutes ago” or “5 years ago”) so that you don’t need to calculate that in your brain. You can write code to solve this problem on your own, but Humanizer has it already put into a simple extension method Humanize() on the DateTime class:

 

A week from a TimeSpan

The same magic works with TimeSpan objects, where Humanizer will show a unit of time that fits best:

 

10.5 MB for files

It can be helpful to know how big a file is before you try to download it on a mobile connection. However, just showing the size in bytes may not help your users. Humanizer offers its own class to represent file sizes that can be converted as you need it or shown again in a human readable form:

 

Truncate Strings

You can truncate Strings with just a method call. Than can work, but often you need to indicate that this string was shortened and that requires some sort of logic. Humanizer can help you with this problem as well:

 

Roman Numerals

Should you deal with roman numerals you can use Humanizer to convert Arabic numerals to Roman and back:

 

Internationalisation

The best part about Humanizer is the support for multiple languages. It uses the environment settings and each call to Humanize() can be overwritten with a specific CultureInfo:

 

Great, but I need different units

The Humanize() method offers various options to change the units it displays. The precision is a good starting point to get more details from Humanizer:

The parameter maxUnit can help you to get smaller units back from a call to Humanize():

You find in the Readme.md of Humanizer many more examples on how you can influence the output for various data types. If you search for precision, maxUnit or minUnit you should find them without much effort.

 

Conclusion

Humanizer is a great help when you need to format output in a human readable form. It doesn’t look like much, but you safe a lot of time when you use this library instead of writing the code on your own.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.