Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C# 4.0

A Money type for the CLR

Rate me:
Please Sign up or sign in to vote.
4.90/5 (62 votes)
18 Mar 2013Ms-PL14 min read 194.2K   2.5K   138  
A convenient, high-performance money structure for the CLR which handles arithmetic operations, currency types, formatting, and careful distribution and rounding without loss.
using System;
using System.Globalization;
using Xunit;

namespace System.Tests
{
    public class CurrencyTests
    {
        [Fact]
        public void CurrencyFromCurrentCultureEqualsCurrentCultureCurrency()
        {
            // NOTE: I think this test could fail in certain cultures...
            var currency1 = new Currency(new RegionInfo(CultureInfo.CurrentCulture.LCID).ISOCurrencySymbol);
            var currency2 = Currency.FromCurrentCulture();

            Assert.Equal(currency1.Name, currency2.Name);
            Assert.Equal(currency1.Symbol, currency2.Symbol);
            Assert.Equal(currency1.Iso3LetterCode, currency2.Iso3LetterCode);
            Assert.Equal(currency1.IsoNumericCode, currency2.IsoNumericCode);
        }

        [Fact]
        public void CurrencyFromSpecificCultureInfoIsCorrect()
        {
            var currency = Currency.FromCultureInfo(new CultureInfo(1052));

            Assert.Equal(8, currency.IsoNumericCode);
        }

        [Fact]
        public void CurrencyFromSpecificIsoCodeIsCorrect()
        {
            var currency = Currency.FromIso3LetterCode("EUR");
            
            Assert.Equal(978, currency.IsoNumericCode);
        }

        [Fact]
        public void CurrencyHasValueEquality()
        {
            var currency1 = new Currency("USD");
            var currency2 = new Currency("USD");
            object boxedCurrency2 = currency2;

            Assert.True(currency1.Equals(currency2));
            Assert.True(currency1.Equals(boxedCurrency2));
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Architect
United States United States
I'm a software engineer with 25 years of experience in areas from game and simulation development, enterprise development, systems management, machine learning, real-time and embedded systems development and geospaitial systems development.

You can find more of my work at http://www.codeplex.com and my articles at http://vectordotnet.blogspot.com/ and http://dotnoted.spaces.live.com.

Comments and Discussions