Skip to content

Instantly share code, notes, and snippets.

@vext01
Created May 13, 2013 20:03
Show Gist options
  • Save vext01/5571045 to your computer and use it in GitHub Desktop.
Save vext01/5571045 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 idx = index s '.' in
let len = length s in
let whole = sub s 0 idx in
let frac = sub s (idx + 1) (len - idx - 1) in
let scale = power_num (num_of_int 10) (num_of_int (length frac)) in
let conc = concat "" [whole; frac] in
let move_dp = num_of_string conc in
let n = div_num move_dp scale 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