tags:

views:

465

answers:

5

Can you suggest a best way to define money type in F#?

A: 

use a long, and store pennies (or tenths of a penny) in it.

You could use a class like Decimal, but that usually ends up being quite slow.

gbjbaanb
shouldn't correctness be more important than speed in this case?
Erich Mirabal
how is using an integer type to store the smallest unit not accurate. Its not like using a double type.
gbjbaanb
Dangerous. Besides the high chance of error, you can later have problems when someone says the tax rate is $0.001 per unit.
Jonathan Allen
+7  A: 

Always, always, use System.Decimal for storing financial data! (Unless you dont care about inaccuracy and rounding errors!) http://msdn.microsoft.com/en-us/library/364x0z75(VS.71).aspx

Fraser
I know that is the c# reference but the info holds true to f# as well...
Fraser
So F# measures don't provide any additional benefits to financial applications?
Sergej Andrejev
+4  A: 

type money = int<dollars>?

Haven't even tried it to see... can you define arbitrary units, or does it only work with explicitly defined ones?

Obviously you'd probably want

type money = int<thousandths_of_currency> (or tens of pennies, or whatever).

To be more accurate.

edited:

decimals take types so you can define money as:

[<Measure>]

type = pounds

type money = decimal<pounds>

which could ensure currencies aren't cross converted by accident, eg:

if

balance = decimal<pounds>

and

payment = decimal<dollars>

newbalance = balance + payment

will not compile, and you'll have to convert payment to decimal<pounds>

Massif
I don't get what is your suggestion :( F# allows to define arbitrary units.
Sergej Andrejev
aww... looks like units only apply to floats! curses.
Massif
F# allows you to define units of measure for a number type. So you can define a type length = float<metres> and the units will be preserved through calculations.See: http://blogs.msdn.com/andrewkennedy/archive/tags/Units+of+Measure/default.aspx
Massif
But, joy of joys.. you can define units of measure onto decimals![<Measure>]type = dollarstype money = decimal<dollars>
Massif
As of May 2009 CTP, you can apparently also apply units of measure to ints (though what help this would be for money, I'm not sure).
Benjol
+1  A: 

Luca Bolognese suggests one defines their own Money type based off of float:

[<Measure>] type money
let money (f:float) = f * 1.<money>
Ben Griswold
A: 

F# now has built in support for Measures and Units. According to the lead engineer for this feature, Kennedy it is aimed at financial apps among other solutions.

So I would look at that before defining my own money type in F#.

Werner

Werner Keil