Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
module FormatExample2

// <Snippet2>
open System

type CustomerFormatter() =
interface IFormatProvider with
member this.GetFormat(formatType) =
if formatType = typeof<ICustomFormatter> then
this
else
null

interface ICustomFormatter with
member this.Format(format, arg, formatProvider: IFormatProvider) =
if this.Equals formatProvider |> not then
null
else
let format =
if String.IsNullOrEmpty format then "G"
else format.ToUpper()

let customerString =
let s = string arg
if s.Length < 8 then
s.PadLeft(8, '0')
else s

match format with
| "G" ->
customerString.Substring(0, 1) + "-" +
customerString.Substring(1, 5) + "-" +
customerString.Substring 6
| "S" ->
customerString.Substring(0, 1) + "/" +
customerString.Substring(1, 5) + "/" +
customerString.Substring 6
| "P" ->
customerString.Substring(0, 1) + "." +
customerString.Substring(1, 5) + "." +
customerString.Substring 6
| _ ->
raise (FormatException $"The '{format}' format specifier is not supported.")

let acctNumber = 79203159
String.Format(CustomerFormatter(), "{0}", acctNumber)
|> printfn "%s"
String.Format(CustomerFormatter(), "{0:G}", acctNumber)
|> printfn "%s"
String.Format(CustomerFormatter(), "{0:S}", acctNumber)
|> printfn "%s"
String.Format(CustomerFormatter(), "{0:P}", acctNumber)
|> printfn "%s"
try
String.Format(CustomerFormatter(), "{0:X}", acctNumber)
|> printfn "%s"
with :? FormatException as e ->
printfn $"{e.Message}"

// The example displays the following output:
// 7-92031-59
// 7-92031-59
// 7/92031/59
// 7.92031.59
// The 'X' format specifier is not supported.
// </Snippet2>
17 changes: 17 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/format4.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module format4

// <Snippet4>
open System

let formatString =
" {0,10} ({0,8:X8})\nAnd {1,10} ({1,8:X8})\n = {2,10} ({2,8:X8})"

let value1 = 16932
let value2 = 15421
String.Format(formatString, value1, value2, value1 &&& value2)
|> printfn "%s"
// The example displays the following output:
// 16932 (00004224)
// And 15421 (00003C3D)
// = 36 (00000024)
// </Snippet4>
24 changes: 24 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/format5.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module format5

open System

// <Snippet5>
let date1 = DateTime(2009, 7, 1)
let hiTime = TimeSpan(14, 17, 32)
let hiTemp = 62.1m
let loTime = TimeSpan(3, 16, 10)
let loTemp = 54.8m

String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", date1, hiTime, hiTemp, loTime, loTemp)
|> printfn "%s\n"

String.Format("Temperature on {0:d}:\n{1,11}: {2} degrees (hi)\n{3,11}: {4} degrees (lo)", [| date1 :> obj; hiTime; hiTemp; loTime; loTemp |])
|> printfn "%s"
// The example displays output like the following:
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
// Temperature on 7/1/2009:
// 14:17:32: 62.1 degrees (hi)
// 03:16:10: 54.8 degrees (lo)
// </Snippet5>
30 changes: 30 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/format7.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
module format7

open System

// <Snippet7>
let birthdate = DateTime(1993, 7, 28)
let dates =
[ DateTime(1993, 8, 16)
DateTime(1994, 7, 28)
DateTime(2000, 10, 16)
DateTime(2003, 7, 27)
DateTime(2007, 5, 27) ]

for dateValue in dates do
let interval = dateValue - birthdate
// Get the approximate number of years, without accounting for leap years.
let years = (int interval.TotalDays) / 365
// See if adding the number of years exceeds dateValue.
if birthdate.AddYears years <= dateValue then
String.Format("You are now {0} years old.", years)
else
String.Format("You are now {0} years old.", years - 1)
|> printfn "%s"
// The example displays the following output:
// You are now 0 years old.
// You are now 1 years old.
// You are now 7 years old.
// You are now 9 years old.
// You are now 13 years old.
// </Snippet7>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
module format_paramarray1

// <Snippet10>
open System

type CityInfo =
{ Name: string
Population: int
Area: Decimal
Year: int }

let showPopulationData city =
let args: obj[] = [| city.Name; city.Year; city.Population; city.Area |]
String.Format("{0} in {1}: Population {2:N0}, Area {3:N1} sq. feet", args)
|> printfn "%s"

{ Name = "New York"; Population = 8175133; Area = 302.64m; Year = 2010 }
|> showPopulationData


{ Name = "Seattle"; Population = 608660; Area = 83.94m; Year = 2010 }
|> showPopulationData

// The example displays the following output:
// New York in 2010: Population 8,175,133, Area 302.6 sq. feet
// Seattle in 2010: Population 608,660, Area 83.9 sq. feet
// </Snippet10>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module formatexample4

// <Snippet6>
open System
open System.Collections.Generic

let temperatureInfo = Dictionary<DateTime, float>()
temperatureInfo.Add(DateTime(2010, 6, 1, 14, 0, 0), 87.46)
temperatureInfo.Add(DateTime(2010, 12, 1, 10, 0, 0), 36.81)

printfn $"Temperature Information:\n"
for item in temperatureInfo do
String.Format("Temperature at {0,8:t} on {0,9:d}: {1,5:N1}°F", item.Key, item.Value)
|> printfn "%s"
// The example displays output like the following:
// Temperature Information:
//
// Temperature at 2:00 PM on 6/1/2010: 87.5°F
// Temperature at 10:00 AM on 12/1/2010: 36.8°F
// </Snippet6>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module formatoverload1

// <Snippet8>
open System

let dat = DateTime(2012, 1, 17, 9, 30, 0)
let city = "Chicago"
let temp = -16
String.Format("At {0} in {1}, the temperature was {2} degrees.", dat, city, temp)
|> printfn "%s"
// The example displays output like the following:
// At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
// </Snippet8>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module formatoverload2

open System

// <Snippet9>
// Create a list of 5-tuples with population data for three U.S. cities, 1940-1950.
let cities =
[ "Los Angeles", DateTime(1940, 1, 1), 1504277, DateTime(1950, 1, 1), 1970358
"New York", DateTime(1940, 1, 1), 7454995, DateTime(1950, 1, 1), 7891957
"Chicago", DateTime(1940, 1, 1), 3396808, DateTime(1950, 1, 1), 3620962
"Detroit", DateTime(1940, 1, 1), 1623452, DateTime(1950, 1, 1), 1849568 ]

// Display header
String.Format("{0,-12}{1,8}{2,12}{1,8}{2,12}{3,14}\n", "City", "Year", "Population", "Change (%)")
|> printfn "%s"

for name, year1, pop1, year2, pop2 in cities do
String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
name, year1, pop1, year2, pop2,
double (pop2 - pop1) / double pop1)
|> printfn "%s"
// The example displays the following output:
// City Year Population Year Population Change (%)
//
// Los Angeles 1940 1,504,277 1950 1,970,358 31.0 %
// New York 1940 7,454,995 1950 7,891,957 5.9 %
// Chicago 1940 3,396,808 1950 3,620,962 6.6 %
// Detroit 1940 1,623,452 1950 1,849,568 13.9 %
// </Snippet9>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module formatsyntax1

// <Snippet12>
open System

String.Format("{0,-10:C}", 126347.89m)
|> printfn "%s"
// </Snippet12>
21 changes: 21 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/fs.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,33 @@
<Compile Include="example1.fs" />
<Compile Include="example2.fs" />
<Compile Include="example3.fs" />
<Compile Include="format_paramarray1.fs" />
<Compile Include="format4.fs" />
<Compile Include="format5.fs" />
<Compile Include="format7.fs" />
<Compile Include="FormatExample2.fs" />
<Compile Include="FormatExample4.fs" />
<Compile Include="formatoverload1.fs" />
<Compile Include="formatoverload2.fs" />
<Compile Include="formatsyntax1.fs" />
<Compile Include="iformattable1.fs" />
<Compile Include="iformattable2.fs" />
<Compile Include="iformattable3.fs" />
<Compile Include="iformattable4.fs" />
<Compile Include="interceptor2.fs" />
<Compile Include="qa-interpolated1.fs" />
<Compile Include="qa-interpolated2.fs" />
<Compile Include="qa1.fs" />
<Compile Include="qa2.fs" />
<Compile Include="qa3.fs" />
<Compile Include="qa11.fs" />
<Compile Include="qa21.fs" />
<Compile Include="qa26.fs" />
<Compile Include="qa27.fs" />
<Compile Include="qa28.fs" />
<Compile Include="qa29.fs" />
<Compile Include="starting1.fs" />
<Compile Include="starting2.fs" />
<Compile Include="starting3.fs" />
</ItemGroup>
</Project>
109 changes: 109 additions & 0 deletions snippets/fsharp/System/FormatException/Overview/interceptor2.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
module interceptor2

// <Snippet11>
open System
open System.Globalization

type InterceptProvider() =
interface IFormatProvider with
member this.GetFormat(formatType) =
if formatType = typeof<ICustomFormatter> then
this
else
null
interface ICustomFormatter with
member _.Format(format, obj, provider: IFormatProvider) =
// Display information about method call.
let formatString =
if format = null then "<null>" else format
printfn $"Provider: {provider.GetType().Name}, Object: %A{obj}, Format String: %s{formatString}"

if obj = null then
String.Empty
else
// If this is a byte and the "R" format string, format it with Roman numerals.
match obj with
| :? byte as value when formatString.ToUpper().Equals "R" ->
let mutable returnString = String.Empty

// Get the hundreds digit(s)
let struct (result, remainder) = Math.DivRem(value, 100uy)
if result > 0uy then
returnString <- String('C', int result)
let value = byte remainder
// Get the 50s digit
let struct (result, remainder) = Math.DivRem(value, 50uy)
if result = 1uy then
returnString <- returnString + "L"
let value = byte remainder
// Get the tens digit.
let struct (result, remainder) = Math.DivRem(value, 10uy)
if result > 0uy then
returnString <- returnString + String('X', int result)
let value = byte remainder
// Get the fives digit.
let struct (result, remainder) = Math.DivRem(value, 5uy)
if result > 0uy then
returnString <- returnString + "V"
let value = byte remainder
// Add the ones digit.
if remainder > 0uy then
returnString <- returnString + String('I', int remainder)

// Check whether we have too many X characters.
let pos = returnString.IndexOf "XXXX"
if pos >= 0 then
let xPos = returnString.IndexOf "L"
returnString <-
if xPos >= 0 && xPos = pos - 1 then
returnString.Replace("LXXXX", "XC")
else
returnString.Replace("XXXX", "XL")
// Check whether we have too many I characters
let pos = returnString.IndexOf "IIII"
if pos >= 0 then
returnString <-
if returnString.IndexOf "V" >= 0 then
returnString.Replace("VIIII", "IX")
else
returnString.Replace("IIII", "IV")
returnString

// Use default for all other formatting.
| :? IFormattable as x ->
x.ToString(format, CultureInfo.CurrentCulture)
| _ ->
string obj

let n = 10
let value = 16.935
let day = DateTime.Now
let provider = InterceptProvider()
String.Format(provider, "{0:N0}: {1:C2} on {2:d}\n", n, value, day)
|> printfn "%s"
String.Format(provider, "{0}: {1:F}\n", "Today: ", DateTime.Now.DayOfWeek)
|> printfn "%s"
String.Format(provider, "{0:X}, {1}, {2}\n", 2uy, 12uy, 199uy)
|> printfn "%s"
String.Format(provider, "{0:R}, {1:R}, {2:R}\n", 2uy, 12uy, 199uy)
|> printfn "%s"
// The example displays the following output:
// Provider: InterceptProvider, Object: 10, Format String: N0
// Provider: InterceptProvider, Object: 16.935, Format String: C2
// Provider: InterceptProvider, Object: 1/31/2013 6:10:28 PM, Format String: d
// 10: $16.94 on 1/31/2013
//
// Provider: InterceptProvider, Object: Today: , Format String: <null>
// Provider: InterceptProvider, Object: Thursday, Format String: F
// Today: : Thursday
//
// Provider: InterceptProvider, Object: 2, Format String: X
// Provider: InterceptProvider, Object: 12, Format String: <null>
// Provider: InterceptProvider, Object: 199, Format String: <null>
// 2, 12, 199
//
// Provider: InterceptProvider, Object: 2, Format String: R
// Provider: InterceptProvider, Object: 12, Format String: R
// Provider: InterceptProvider, Object: 199, Format String: R
// II, XII, CXCIX
// </Snippet11>
Loading