Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define money type in F#

Tags:

types

f#

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

like image 642
Sergej Andrejev Avatar asked May 21 '09 13:05

Sergej Andrejev


People also ask

What do you mean by money?

Money is a commodity accepted by general consent as a medium of economic exchange. It is the medium in which prices and values are expressed. It circulates from person to person and country to country, facilitating trade, and it is the principal measure of wealth.

What is difference between currency and money?

Money is anything which is generally accepted as a medium of exchange and currency is authorized by the government to be treated as money in the nation.

Is money a currency?

The terms money and currency are often thought to mean the same thing. However, while related, they have different meanings. Money is a broader term that refers to an intangible system of value that makes the exchange of goods and services possible, now and in the future. Currency is simply one, tangible form of money.

What is money and how it works?

You just need a market in which to sell your goods or services. In that market, you don't barter for individual goods. Instead you exchange your goods or services for a common medium of exchange—that is, money. You can then use that money to buy what you need from others who also accept the same medium of exchange.


4 Answers

Always, always, use System.Decimal for storing financial data! (Unless you dont care about inaccuracy and rounding errors!) https://docs.microsoft.com/dotnet/api/system.decimal

like image 170
Fraser Avatar answered Sep 28 '22 08:09

Fraser


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>

like image 41
Massif Avatar answered Sep 28 '22 08:09

Massif


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

[<Measure>] type money
let money (f:float) = f * 1.<money>
like image 44
Ben Griswold Avatar answered Sep 28 '22 10:09

Ben Griswold


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

like image 32
Werner Keil Avatar answered Sep 28 '22 09:09

Werner Keil