How does one use sprintf to format an integer to display commas as thousands separators?
I know how to do it using String.Format, but I can't find a way to do it using sprintf.
EDIT: Based on Fyodor Soikin's comment below, I tried this code:
printf "%a" (fun writer (value:int) -> writer.Write("{0:#,#}", value)) 10042
let s = sprintf "%a" (fun writer (value:int) -> writer.Write("{0:#,#}", value)) 10042
The printf call works (but writes to standard output, whereas I want to get a string I can assign to the Text or Content property of a WPF control, for instance).
The sprintf call fails with error FS0039: The field, constructor or member 'Write' is not defined.
If I could fix this error, then this might be the most direct solution possible, and when combined with partial application would be as concise as a built-in version.
Since you can't do that with the Printf module, I do it like this:
/// 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))
And then call it like this:
someNumber |> stringf "N0"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With