Skip to content

Instantly share code, notes, and snippets.

@egelmex
Forked from vext01/parse_dec.ml
Last active December 17, 2015 07:09
Show Gist options
  • Save egelmex/5571067 to your computer and use it in GitHub Desktop.
Save egelmex/5571067 to your computer and use it in GitHub Desktop.
(*
* Parsing a decimal into an arbitrary precision number in Ocaml.
*
* Input not checked as the parser will sanitise the input.
*
* ocamlfind ocamlc -package num -linkpkg -o parse_dec parse_dec.ml
*)
open Num
open String
let num_of_dec_string s =
let dot_index = index s '.' in
let lhs = sub s 0 dot_index in
let rhs = sub s (idx + 1) (len - idx - 1) in
let numerator = concat "" [lhs;rhs] in
let denominator = power_num (num_of_int 10) (length rhs) in
let n = num_of_string (concat "" [numerator; "\"; denominator]) in
Printf.printf "%s.%s=%s\n" whole frac (string_of_num n);;
while true do
let line = read_line () in
num_of_dec_string line
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment