使用 Math.Round 和计量单位

Using Math.Round with a Unit of Measure

我正在尝试在函数中使用 Math.Round 来四舍五入货币金额,如下所示:

let calculateTaxablePayToDate previousPayToDate taxablePayThisMonth =
    taxablePayThisMonth
    |> fun (x:decimal) -> Math.Round(x)
    |> fun x -> x + previousPayToDate 

我传递的类型都是 decimal<GBP> 类型。当我尝试通过函数 运行 它们时,虽然我得到:

This expression was expected to have type
decimal but here has type
int<GBP>

如何在附有度量单位的图形上使用 Math.Round

Math.Round 需要原始值,而不是度量值。您可以将其包装在度量类型的通用函数中:

open System
open Microsoft.FSharp.Core.LanguagePrimitives

let roundMeasure<[<Measure>]'u>(x: decimal<'u>): decimal<'u> = Math.Round(decimal x) |> DecimalWithMeasure

然后你应该能够做到:

let calculateTaxablePayToDate previousPayToDate taxablePayThisMonth =
        taxablePayThisMonth |> roundMeasure |> fun x -> x + previousPayToDate

let calculateTaxablePayToDate previousPayToDate taxablePayThisMonth =
    previousPayToDate + (roundMeasure taxablePayThisMonth)