-
Notifications
You must be signed in to change notification settings - Fork 30
Description
Original bug ID: 4553
Reporter: zack
Status: acknowledged (set by @damiendoligez on 2008-08-04T15:21:21Z)
Resolution: open
Priority: normal
Severity: feature
Version: 3.10.1
Category: otherlibs
Bug description
It seems that Num.num_of_string works only on strings denoting integers:
Num.num_of_string "1.5";;
Exception: Failure "num_of_string".
Supporting decimal numbers appears to be quite easy: numbers such as "1.5" can be mapped to the Ratio.ratio "15/10" and then injected to Num using the Num.Ratio constructor. The change will be backward compatible as the new functionality can be triggered only when the input string contain a '.', situation which currently raise the Failure above.
Can you please consider adding support for decimal numbers in the Num.num_of_string function?
A sample implementation (relying on the current implementation of Num.num_of_string for integer strings) is reported below in the additional information section.
Cheers.
Additional information
let my_num_of_string s =
let dot_pos = try Some (String.index s '.') with Not_found -> None in
match dot_pos with
| None -> Num.num_of_string s
| Some i -> (* e.g.: s = "45.6789", i = 2 )
let len = String.length s in
let numerator = ( e.g. "45" ^ "6789" = "456789" )
String.sub s 0 i ^ String.sub s (i + 1) (len - (i + 1)) in
let denominator = ( e.g. <big_int 10000> *)
Big_int.power_int_positive_int 10 (len - (i + 1)) in
Num.Ratio (Ratio.create_ratio (big_int_of_string numerator) denominator)