如何使用sprintf格式化整数,逗号为千位分隔符

时间:2016-03-28 23:03:40

标签: f# inline

如何使用sprintf格式化整数以将逗号显示为千位分隔符?

我知道如何使用String.Format来做,但我找不到使用sprintf的方法。

编辑:根据下面的Fyodor Soikin的评论,我尝试了这段代码:

printf "%a" (fun writer (value:int) -> writer.Write("{0:#,#}", value)) 10042
let s = sprintf "%a" (fun writer (value:int) -> writer.Write("{0:#,#}", value)) 10042

printf调用有效(但写入标准输出,而我想获取一个我可以分配给WPF控件的Text或Content属性的字符串)。

sprintf调用失败,错误为FS0039:字段,构造函数或成员'写入'没有定义。

如果我可以修复此错误,那么这可能是最直接的解决方案,并且当与部分应用程序结合使用时,将与内置版本一样简洁。

3 个答案:

答案 0 :(得分:2)

由于你不能用Printf模块做到这一点,我这样做:

/// Calls ToString on the given object, passing in a format-string value.
let inline stringf format (x : ^a) = 
    (^a : (member ToString : string -> string) (x, format))

然后像这样称呼它:

someNumber |> stringf "N0"

答案 1 :(得分:1)

这样可行,但应该有一种更简单的方法。

let thousands(x:int64) = 
    System.String.Format("{0:#,0}", x)

let s = sprintf "%s" (thousands(0L))
printfn "%s" s

let s = sprintf "%s" (thousands(1L))
printfn "%s" s

let s = sprintf "%s" (thousands(1000L))
printfn "%s" s

let s = sprintf "%s" (thousands(1000000L))
printfn "%s" s

0
1
1,000
1,000,000

稍微好一点的版本

let printNumber (x : int) : string =
    System.String.Format("{0:N0}",x)

答案 2 :(得分:0)

这是一个功能:

let thousands n =
    let v = (if n < 0 then -n else n).ToString()
    let r = v.Length % 3 
    let s = if r = 0 then 3 else r
    [   yield v.[0.. s - 1]
        for i in 0..(v.Length - s)/ 3 - 1 do
            yield v.[i * 3 + s .. i * 3 + s + 2]
    ]
    |> String.concat ","
    |> fun s -> if n < 0 then "-" + s else s

这是另一个带有一些辅助扩展成员的

type System.String with
    member this.Substring2(from, n) = 
        if   n    <= 0           then ""
        elif from >= this.Length then ""
        elif from <  0           then this.Substring2(0, n + from)
        else this.Substring(from, min n (this.Length - from))
    member this.Left             n  = if n < 0 
                                    then this.Substring2(0, this.Length + n)
                                    else this.Substring2(0, n              )
    member this.Right            n  = this.Substring2(max 0 (this.Length - n), this.Length)

let thousands (n:int) =
    let rec thousands acc = 
        function
        | "" -> acc
        | x  -> thousands (x.Right 3 + if acc = "" then "" else "," + acc) (x.Left -3)
    if n < 0 then -n else n
    |> string
    |> thousands ""
    |> fun s -> if n < 0 then "-" + s else s