Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Makes life working with units of measurement just a little bit better.

License

NotificationsYou must be signed in to change notification settings

angularsen/UnitsNet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Build StatuscodecovStandWithUkraine

Units.NET

Add strongly typed quantities to your code and get merrily on with your life.

No more magic constants found on Stack Overflow, no more second-guessing the unit of parameters and variables.

Changes

ℹ️ Themaster branch now targets v6, but it is still in pre-release.New units will be backported tomaintenance/v5 until v6 becomes stable.

Upgrading from 5.x to 6.x
Upgrading from 4.x to 5.x

Overview

Installing via NuGet

Add it via CLI:

dotnet add package UnitsNet

or go toNuGet Gallery | UnitsNet for detailed instructions.

Build Targets

  • .NET Standard 2.0
  • .NET 8.0 (LTS)
  • .NET 9.0 (latest stable)
  • .NET 10.0 (preview)
  • .NET nanoFramework

Extension Packages

UnitsNet.NumberExtensions.CS14 (C# 14 Extension Members)

For C# 14 projects, use the new extension members syntax (no parentheses):

dotnet add package UnitsNet.NumberExtensions.CS14
usingUnitsNet.NumberExtensions.NumberToLength;// C# 14 extension members syntax, without paranthesesLengthdistance=5.Meters;// Instead of Length.FromMeters(5)

Note: Requires 'preview' and .NET 10 SDK preview for now.

UnitsNet.NumberExtensions (Classic)

For C# 13 and lower (.NET SDK 9 or lower), use the classic extension methods:

dotnet add package UnitsNet.NumberExtensions
usingUnitsNet.NumberExtensions.NumberToLength;// Classic extension methods, with parenthesesLengthdistance=5.Meters();// Instead of Length.FromMeters(5)

Static Typing

// ConstructLengthmeter=Length.FromMeters(1);LengthtwoMeters=newLength(2,LengthUnit.Meter);// Convertdoublecm=meter.Centimeters;// 100doubleyards=meter.Yards;// 1.09361doublefeet=meter.Feet;// 3.28084doubleinches=meter.Inches;// 39.3701// Pass quantity types instead of values to avoid conversion mistakes and communicate intentstringPrintPersonWeight(Massweight){// Compile error! Newtons belong to Force, not Mass. A common source of confusion.doubleweightNewtons=weight.Newtons;// Convert to the unit of choice - when you need itreturn$"You weigh{weight.Kilograms:F1} kg.";}

Operator Overloads

// ArithmeticLengthl1=2*Length.FromMeters(1);Lengthl2=Length.FromMeters(1)/2;Lengthl3=l1+l2;// Construct between unitsLengthdistance=Speed.FromKilometersPerHour(80)*TimeSpan.FromMinutes(30);Accelerationa1=Speed.FromKilometersPerHour(80)/TimeSpan.FromSeconds(2);Accelerationa2=Force.FromNewtons(100)/Mass.FromKilograms(20);RotationalSpeedr=Angle.FromDegrees(90)/TimeSpan.FromSeconds(2);

Culture and Localization

The culture for abbreviations defaults to Thread.CurrentCulture and falls back to US English if not defined. Thread.CurrentCulture affects number formatting unless a custom culture is specified. The relevant methods are:

  • ToString()
  • GetAbbreviation()
  • Parse/TryParse()
  • ParseUnit/TryParseUnit()
varusEnglish=newCultureInfo("en-US");varrussian=newCultureInfo("ru-RU");varoneKg=Mass.FromKilograms(1);// ToString() uses CurrentCulture for abbreviation language number formatting. This is consistent with the behavior of the .NET Framework,// where DateTime.ToString() uses CurrentCulture for the whole string, likely because mixing an english date format with a russian month name might be confusing.CultureInfo.CurrentCulture=russian;stringkgRu=oneKg.ToString();// "1 кг"// ToString() with specific culture and custom string format patternstringmgUs=oneKg.ToUnit(MassUnit.Milligram).ToString(usEnglish,"unit: {1}, value: {0:F2}");// "unit: mg, value: 1.00"stringmgRu=oneKg.ToUnit(MassUnit.Milligram).ToString(russian,"unit: {1}, value: {0:F2}");// "unit: мг, value: 1,00"// Parse measurement from stringMasskg=Mass.Parse("1.0 kg",usEnglish);// Parse unit from string, a unit can have multiple abbreviationsRotationalSpeedUnitrpm1=RotationalSpeed.ParseUnit("rpm");// RotationalSpeedUnit.RevolutionPerMinuteRotationalSpeedUnitrpm2=RotationalSpeed.ParseUnit("r/min");// RotationalSpeedUnit.RevolutionPerMinute// Get default abbreviation for a unit, the first if more than one is defined in Length.json for Kilogram unitstringkgAbbreviation=Mass.GetAbbreviation(MassUnit.Kilogram);// "kg"

Gotcha: AmbiguousUnitParseException

Some units of a quantity have the same abbreviation, which means.Parse() is not able to know what unit you wanted.Unfortunately there is no built-in way to avoid this, either you need to ensure you don't pass in input that cannot be parsed or you need to write your own parser that has more knowledge of preferred units or maybe only a subset of the units.

Example:Length.Parse("1 pt") throwsAmbiguousUnitParseException with messageCannot parse "pt" since it could be either of these: DtpPoint, PrinterPoint.

Dynamically Parse Quantities and Convert to Units

Sometimes you need to work with quantities and units at runtime, such as parsing user input.

There are a handful of classes to help with this:

  • Quantity for parsing and constructing quantities as well as looking up units, names and quantity information dynamically
  • UnitConverter for converting values to a different unit, with only strings or enum values
  • UnitParser for parsing unit abbreviation strings, such as"cm" toLengthUnit.Centimeter

Quantity - Enumerate quantities and units at runtime

UseQuantity class for looking upQuantityInfo andUnitInfo at runtime.

string[]names=Quantity.Names;// ["Length", "Mass", ...]QuantityInfo[]qis=Quantity.Infos;// All quantities and their units, types, values.// Look up quantity by name.QuantityInfolengthInfo=Quantity.ByName["Length"];UnitInfo[]lengthUnits=lengthInfo.UnitInfos;// Look up unit by enum value (note: for extensibility, will instead look up by name in the future)UnitInfocmInfo=Quantity.GetUnitInfo(LengthUnit.Centimeter);

QuantityInfo - Information about a quantity

QuantityInfo makes it easy to get names, units, types and values for a quantity.This is useful for populating lists of quantities and units for the user to choose.

// Different ways to look up the quantity info.QuantityInfolengthInfo=Quantity.ByName["Length"];lengthInfo=Length.Info;lengthInfo=Length.FromMeters(1).QuantityInfo;// The quantity information.lengthInfo.Name;// "Length"lengthInfo.UnitInfos;// UnitInfo[] for its units Centimeter, Meter, etc.lengthInfo.BaseUnitInfo;// UnitInfo for LengthUnit.MeterlengthInfo.BaseDimensions;// {"Length": 1, "Mass": 0, ...}lengthInfo.UnitType;// typeof(LengthUnit)lengthInfo.ValueType;// typeof(Length)lengthInfo.Zero;// Length.Zero

UnitInfo - Information about a unit

UnitInfo describes a unit, such as its enum value, names and its representation in SI base units.

// Different ways to look up the unit info.varcm=Quantity.GetUnitInfo(LengthUnit.Centimeter);if(Quantity.TryGetUnitInfo(LengthUnit.Centimeter,outUnitInfotryGetCm)){cm=tryGetCm;}// The unit information.cm.Value;// Enum value: LengthUnit.Centimetercm.Name;// "Centimeter"cm.PluralName;// "Centimeters"cm.BaseUnits;// {"Length": Centimeter, "Mass": null, "Time": null, ...}

Construct quantity

All you need is the value and the unit enum value.

IQuantityquantity=Quantity.From(3,LengthUnit.Centimeter);// Lengthif(Quantity.TryFrom(3,LengthUnit.Centimeter,outIQuantityquantity2)){}

You can also construct from strings, such as mapping between DTO types in an API:

IQuantityquantity=Quantity.From(value:3,quantityName:"Length",unitName:"Centimeter");if(Quantity.TryFrom(value:3,quantityName:"Length",unitName:"Centimeter",outIQuantity?quantity2)){}

Or create by just the unit abbreviation, as long as there is exactly one unit with this abbreviation.

// Length with unit LengthUnit.CentimeterIQuantityquantity=Quantity.FromUnitAbbreviation(3,"cm");if(Quantity.TryFromUnitAbbreviation(3,"cm",outIQuantity?quantity2)){}

Parse quantity

Parse any string to a quantity instance of the given the quantity type.

IQuantityquantity=Quantity.Parse(typeof(Length),"3 cm");// Lengthif(Quantity.TryParse(typeof(Length),"3cm",outIQuantityquantity2){}

Parse unit

UnitParser parses unit abbreviation strings to unit enum values.

Enumunit=UnitsNetSetup.Default.UnitParser.Parse("cm",typeof(LengthUnit));// LengthUnit.Centimeterif(UnitsNetSetup.Default.UnitParser.TryParse("cm",typeof(LengthUnit),outEnumunit2)){// Use unit2 as LengthUnit.Centimeter}

Convert quantity to unit - IQuantity and Enum

Convert anyIQuantity instance to a different unit by providing a target unit enum value.

// Assume these are passed in at runtime, we don't know their values or typeEnumuserSelectedUnit=LengthUnit.Millimeter;IQuantityquantity=Length.FromCentimeters(3);// Later we convert to a unitquantity.ToUnit(userSelectedUnit).Value;// 30quantity.ToUnit(userSelectedUnit).Unit;// LengthUnit.Millimeterquantity.ToUnit(userSelectedUnit).ToString();// "30 mm"quantity.ToUnit(PressureUnit.Pascal);// Throws exception, not compatiblequantity.As(userSelectedUnit);// 30

Convert quantity to unit - From/To Enums

Useful when populating lists with unit enum values for the user to choose.

UnitConverter.Convert(1,LengthUnit.Centimeter,LengthUnit.Millimeter);// 10 mm

Convert quantity to unit - Names or abbreviation strings

Sometimes you only have strings to work with, that works too!

UnitConverter.ConvertByName(1,"Length","Centimeter","Millimeter");// 10 mmUnitConverter.ConvertByAbbreviation(1,"Length","cm","mm");// 10 mm

Custom units

Units.NET allows you to add your own units and quantities at runtime, to represent asIQuantity and reusing Units.NET for parsing and converting between units.

Read more atExtending-with-Custom-Units.

Map between unit enum values and unit abbreviations

// Map unit enum values to unit abbreviationsvarunitAbbreviations=UnitsNetSetup.Default.UnitAbbreviations;unitAbbreviations.MapUnitToDefaultAbbreviation(HowMuchUnit.Some,"sm");unitAbbreviations.GetDefaultAbbreviation(HowMuchUnit.Some);// "sm"UnitsNetSetup.Default.UnitParser.Parse<HowMuchUnit>("sm");// HowMuchUnit.Some

Convert between units of custom quantity

varunitConverter=UnitsNetSetup.Default.UnitConverter;unitConverter.SetConversionFunction<HowMuch>(HowMuchUnit.Lots,HowMuchUnit.Some, x=>newHowMuch(x.Value*2,HowMuchUnit.Some));unitConverter.SetConversionFunction<HowMuch>(HowMuchUnit.Tons,HowMuchUnit.Lots, x=>newHowMuch(x.Value*10,HowMuchUnit.Lots));unitConverter.SetConversionFunction<HowMuch>(HowMuchUnit.Tons,HowMuchUnit.Some, x=>newHowMuch(x.Value*20,HowMuchUnit.Some));varfrom=newHowMuch(10,HowMuchUnit.Tons);IQuantityConvert(HowMuchUnittoUnit)=>unitConverter.GetConversionFunction<HowMuch>(from.Unit,toUnit)(from);Console.WriteLine($"Convert 10 tons to:");Console.WriteLine(Convert(HowMuchUnit.Some));// 200 smConsole.WriteLine(Convert(HowMuchUnit.Lots));// 100 ltsConsole.WriteLine(Convert(HowMuchUnit.Tons));// 10 tns

Parse custom quantity

QuantityParser parses quantity strings toIQuantity by mapping custom units to unit abbreviations inUnitAbbreviationsCache.

// Map custom units to abbreviationsvarunitAbbreviationsCache=UnitsNetSetup.Default.UnitAbbreviations;unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some,"sm");unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.ATon,"tn");varquantityParser=UnitsNetSetup.Default.QuantityParser;// "1 sm" => new HowMuch(1, HowMuchUnit.Some)HowMuchq=quantityParser.Parse<HowMuch,HowMuchUnit>(str:"1 sm",formatProvider:null,fromDelegate:(value,unit)=>newHowMuch((double)value,unit));
// Alternatively, create your own instances to not change the global singleton instances.varunitAbbreviationsCache=UnitAbbreviationsCache.CreateDefault();// or .CreateEmpty()unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some,"sm");unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.ATon,"tn");varquantityParser=newQuantityParser(unitAbbreviationsCache);

Example: Unit converter app

Source code forSamples/UnitConverter.Wpf
Download (release 2018-11-09 for Windows)

image

This example shows how you can create a dynamic unit converter, where the user selects the quantity to convert, such asTemperature, then selects to convert fromDegreeCelsius toDegreeFahrenheit and types in a numeric value for how many degrees Celsius to convert.The quantity list box contains quantity names, such as"Length". The two unit list boxes containEnum values, such asLengthUnit.Meter.

Populate quantity selector

UseQuantity to enumerate all quantity names, such as"Length" and"Mass".

this.Quantities=Quantity.Names;// string[]// orthis.Quantities=Quantity.Infos.Select(i=>i.Name).ToList();

Update unit lists when selecting new quantity

So user can only choose from/to units compatible with the quantity type.

QuantityInfoquantityInfo=Quantity.ByName[quantityName];_units.Clear();foreach(EnumunitValueinquantityInfo.UnitInfos.Select(ui=>ui.Value)){_units.Add(newUnitListItem(unitValue));}

Update calculation on unit selection changed

UsingUnitConverter to convert by unit enum values as given by the list selection"Length" and unit names like"Centimeter" and"Meter".

doubleconvertedValue=UnitConverter.Convert(FromValue,// numeric valueSelectedFromUnit.UnitEnumValue,// Enum, such as LengthUnit.MeterSelectedToUnit.UnitEnumValue);// Enum, such as LengthUnit.Centimeter

Example: WPF app using IValueConverter to parse input

Src:Samples/MvvmSample.Wpf

WpfMvvmSample_219w

The purpose of this app is to show how to create anIValueConverter in order to bind XAML to quantities.

Precision and Accuracy

A base unit is chosen for each unit class, represented by a double value (64-bit), and all conversions go via this unit. This means that there will always be a small error in both representing other units than the base unit as well as converting between units.

Units.NET was intended for convenience and ease of use, not highly accurate conversions, but I am open to suggestions for improvements.

The tests accept an error up to 1E-5 for most units added so far. Exceptions include units like Teaspoon, where the base unit cubic meter is a lot bigger. In many use cases this is sufficient, but for others this may be a showstopper and something you need to be aware of.

For more details, seePrecision.

Serialize to JSON, XML and more

Read the wiki onSerializing to JSON, XML and more.

Want To Contribute?

Continuous Integration

Azure DevOps performs the following:

  • Build and test all branches
  • Build and test pull requests, notifies on success or error
  • Deploy NuGets on master branch, if nuspec versions changed

Who are Using UnitsNet?

It would be awesome to know who are using this library. If you would like your project listed here,create an issue or edit theREADME.md and send a pull request. Max logo size is300x35 pixels and should be in.png,.gif or.jpg formats.

Motion Catalyst logo

Swing Catalyst and Motion Catalyst, Norway

Sports performance applications for Windows and iOS, that combine high-speed video with sensor data to bring facts into your training and visualize the invisible forces at work

Units.NET started here in 2007 when reading strain gauge measurements from force plates and has been very useful in integrating a number of different sensor types into our software and presenting the data in the user's preferred culture and units.

https://www.swingcatalyst.com (for golf)
https://www.motioncatalyst.com (everything else)

- Andreas Gullberg Larsen, CTO (andreas@motioncatalyst.com)

PK Sound logo

PK Sound, Canada

Award-winning performers and composers put everything they’ve got into their music. PK Sound makes sure their fans will hear it all – brilliantly, precisely, consistently.

PK Sound uses UnitsNet in Kontrol - the remote control counterpart to Trinity, the world's only robotic line array solution.

http://www.pksound.ca/pk-sound/announcing-the-official-release-of-kontrol/ (for an idea of what the Kontrol project is)
http://www.pksound.ca/trinity/ (the speakers that Kontrol currently controls)
http://www.pksound.ca/ (everything else)

- Jules LaPrairie, Kontrol software team member

Microsoft.IoT.Devices

Microsoft.IoT.Devices extends Windows IoT Core and makes it easier to support devices like sensors and displays. It provides event-driven access for many digital and analog devices and even provides specialized wrappers for devices like joystick, rotary encoder and graphics display.

http://aka.ms/iotdevices (home page including docs)
http://www.nuget.org/packages/Microsoft.IoT.Devices (NuGet package)

Crawlspace

Software for creating printable hex maps for use in pen and paper RPGs. Botha user-friendly app and a high-level library for generating labelled hexmaps.

https://bitbucket.org/MartinEden/Crawlspace

- Martin Eden, project maintainer

ANSYS, Inc. Logo

ANSYS, Inc. (ANSYS Discovery Live)

ANSYS Discovery Live provides instantaneous 3D simulation, tightly coupled with direct geometry modeling, to enable interactive design exploration and rapid product innovation. It is an interactive experience in which you can manipulate geometry, material types or physics inputs, then instantaneously see changes in performance.

https://www.ansys.comhttps://www.ansys.com/products/3d-design/ansys-discovery-live

- Tristan Milnthorp, Principal Software Architect (tristan.milnthorp@ansys.com)

Primoris Sigma Stargen

Stargen is a decades old software to create realistic planets and satellites from a given Star. It's based on work from various scientists and been used for years. Primoris Sigma Stargen is a C# port of the utility that makes it a Framework to extend it with new algorithms for planetary formation and physics equations.

https://github.com/ebfortin/primoris.universe.stargen

Harrington Hoists logo

Harrington Hoists, Inc. (A Subsidiary of KITO Americas, Inc.)

Harrington Hoists, Inc. is located in Manheim, PA, Elizabethtown, PA, South Holland, IL and Corona, CA. Harrington is a leading manufacturer of manual, electric and air chain hoists as well as wire rope hoists and crane products serving the North American material handling industry.

Harrington uses UnitsNet in their internal software to perform many different calculations related to crane dimensioning, girder strength, electrical safety verification, etc.

https://www.harringtonhoists.com
https://kito.com

- Luke Westfall, Design Automation Engineer

Structural Analysis Format - SDK project

Project logo

The Structural Analysis Format (SAF) has been created to allow structural engineering applications to exchange data using a straight forward and simple to understand format.While inspired by IFC, SAF has its benefits that it'seasily modifiable by the end-user(it's an xlsx file),well documented andeasy to understand.UnitsNet is used by the SDK provided by SCIA to facilitate import / export between metric & imperial systems

https://www.saf.guidehttps://github.com/StructuralAnalysisFormat/StructuralAnalysisFormat-SDK

- Dirk Schuermans, Software Engineer forSCIA nv

Top Usages by GitHub Repos

Produced withghtopdep.

RepoStars
https://github.com/microsoft/PowerToys120K
https://github.com/dotnet/iot2.3K
https://github.com/genielabs/HomeGenie410
https://github.com/raspberry-sharp/raspberry-sharp-io340
https://github.com/nanoframework/nanoFramework.IoT.Device258
https://github.com/porrey/Virtual-ZPL-Printer240
https://github.com/chino-os/chino-os147
https://github.com/BriefFiniteElementNet/BriefFiniteElement.Net156
https://github.com/WhiteBlackGoose/UnitsOfMeasure59
https://github.com/pi-top/pi-top-4-.NET-SDK50

Units.NET on other platforms

Get the same strongly typed units on other platforms, based on the sameunit definitions.

LanguageNamePackageRepositoryMaintainers
JavaScript /
TypeScript
unitsnet-jsnpmgithub@haimkastner
Pythonunitsnet-pypypigithub@haimkastner
Golangunitsnet-gopkg.go.devgithub@haimkastner

[8]ページ先頭

©2009-2025 Movatter.jp