0

I'm learning F# and have an assignment where I have to treat a float as a coordinate. For example float 2.3 would be treated as a coordinate (2.3) where x is 2 and y is 3.

How can I split the float to calculate with it?

I am trying to make a function to calculate the length of a vector: let lenOfVec (1.2, 2.3) and using pythagoras' method to get the length of hypotenuse.

But I am already stuck at splitting up the float.

Hope some can help!

jubibanna
  • 1,095
  • 9
  • 21

2 Answers2

1

Having at your disposal libraries as rich as F#/.NET offer the task of splitting a float into two can be done with one short line of code:

let splitFloat n = n.ToString().Split('.') |> Array.map float
  • library function ToString() converts the argument n (supposedly float) to a string
  • library functionSplit('.') applied to this string converts it into an array of two strings representing the first number before decimal dot and the second number after the dot
  • finally this array of 2 strings is converted by applying library function float to the each array element with the help of just another library function Array.map, producing the array of two sought floats

Being applied to a random float number the outlined chain of conversions looks like

123.456 --> "123.456" --> [|123;456|] --> [|123.0;456.0|]

Gene Belitski
  • 10,270
  • 1
  • 34
  • 54
  • Thanks, a really nice solution :-) Had to use Split(',') for it to work, otherwise it works great. – jubibanna Sep 30 '18 at 16:17
  • If you're writing code that will be used in many countries (some where numbers use `.` as a decimal point and some where they use `,`), then you need to look up the current decimal separator in `NumberFormatInfo`. First do `open System.Globalization`, then do `let sep = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator`. Now you can do `n.ToString().Split(sep, 1, StringSplitOptions.None)`. That's the safest way to write this code if you're intending it to be used in multiple cultures. (If you're just writing it for yourself, though, `Split(',')` is enough. – rmunn Sep 30 '18 at 20:20
0

Stealing from a few other answers on here, something like this seems to work for a few examples:

open System

///Takes in a float and returns a tuple of the the two parts.
let split (n: float) = 
    let x = Math.Truncate(n)

    let bits = Decimal.GetBits(decimal n)
    let count = BitConverter.GetBytes(bits.[3]).[2]    
    let dec = n - x

    let y = dec * Math.Pow(10., float count)

    x, y

Examples:

  • 2.3 -> (2.0, 3.0)
  • 200.123 -> (200.0, 123.0)
  • 5.23 -> (5.0, 23.0)

Getting the X is easy, as you can just truncate the decimal part.

Getting the Y took input from this answer and this one.

DaveShaw
  • 52,123
  • 16
  • 112
  • 141