-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringtonumber.fsx
35 lines (27 loc) · 1.22 KB
/
stringtonumber.fsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
(*
We need a function that can transform a string into a number. What ways of achieving this do you know?
taken from: https://www.codewars.com/kata/convert-a-string-to-a-number/train/fsharp
*)
// let stringToNumber = int
// let n = "12345" |> stringToNumber
open System
open System.Globalization
let stringToNumber (str:string) =
let toNumber text =
let sum, _ = text
|> Seq.rev
|> Seq.takeWhile Char.IsDigit
|> Seq.map (string >> int) // toString, because char |> int gives us the ascii code which we don't want
|> Seq.fold(fun (sum, factor) d -> ((sum + d * factor), factor * 10)) (0, 1)
sum
let numberParts = str.Split([|CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator|], StringSplitOptions.RemoveEmptyEntries)
let number = match numberParts with
|[|f|] -> float(toNumber f)
|[|f;s|] ->
let factor = pown 10. ((s |> Seq.length) * (-1))
float(toNumber f) + (factor * float(toNumber s))
|_ -> 0.
match str |> Seq.head with
|'-' -> number * (-1.)
|_ -> number
let n = "-123,45" |> stringToNumber