Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sprintf to format an integer with commas as thousands separators

Tags:

inline

f#

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.

like image 817
Scott Hutchinson Avatar asked Mar 28 '16 23:03

Scott Hutchinson


1 Answers

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"
like image 185
Joel Mueller Avatar answered Oct 18 '22 10:10

Joel Mueller