Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Num.num_of_string should accept decimal numbers #14

Open
vicuna opened this issue May 8, 2008 · 2 comments
Open

Num.num_of_string should accept decimal numbers #14

vicuna opened this issue May 8, 2008 · 2 comments

Comments

@vicuna
Copy link

vicuna commented May 8, 2008

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)

@nojb
Copy link
Contributor

nojb commented Mar 16, 2019

I guess this should be moved to ocaml/num @xavierleroy

@xavierleroy
Copy link
Contributor

Right, let's move it.

@xavierleroy xavierleroy transferred this issue from ocaml/ocaml Mar 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants