Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

.NET Rational (fraction) value type using Decimals, written in C#

0.00/5 (No votes)
24 Jan 2006 2  
Implements a Rational datatype.

Introduction

The class presented in this article implements a rational value type with basic mathematical functionality.

Using the code

This class has no public constructors.

Implicit casting to/from Int64 (and therefore other integer types) and decimal (and therefore float and double) is supported.

// Cast from int

PIEBALD.Types.Rational a = 1 ;
// Cast from double (via decimal)

PIEBALD.Types.Rational b = 2.3 ;
// Cast from decimal

PIEBALD.Types.Rational c = 4.5M ;

Conversion from decimal can be controlled by the ConversionMethod static property. Currently, the DecimalConversionMethod enumeration defines two values: Decimal and BestGuess. Decimal simply uses a power of ten as the denominator. BestGuess tries (with some success) to determine what numbers can be divided to produce the value.

// This is the default

PIEBALD.Types.Rational.ConversionMethod = 
               DecimalConversionMethod.Decimal;
// Yields 33333333333333333333

//    33333333/10000000000000000000000000000

PIEBALD.Types.Rational d = 1M / 3M ;
PIEBALD.Types.Rational.ConversionMethod = 
             DecimalConversionMethod.BestGuess;
// Yields 1/3

PIEBALD.Types.Rational e = 1M / 3M ;

Strings containing expressions can be assigned with the ParseInfix and ParseRpn methods.

// Convert from string

PIEBALD.Types.Rational f = 
   PIEBALD.Types.Rational.ParseInfix ( "1/2" ) ;
// Convert from string

PIEBALD.Types.Rational g = 
   PIEBALD.Types.Rational.ParseInfix ( "(1/2) / (3/4)" ) ;
// Convert from string

PIEBALD.Types.Rational h = 
   PIEBALD.Types.Rational.ParseRpn ( "1 2 /" ) ;

See my PIEBALD.Lib.LibRpn class for information on how infix is transformed to RPN.

The mathematical operators (+, -, *, /, %, ^ (exponentiation)) are supported. There are other static and instance properties as well.

History

  • First posted - 2006/01/16.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here