Skip to content

Conversation

@glennsl
Copy link
Contributor

@glennsl glennsl commented Dec 30, 2025

Fixes rescript-core/#257

Besides stricter number parsing, this also removes the radix argument in favor of supporting hexadecimal, binary and exponential notation directly.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 30, 2025

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript-lang/rescript@8129

@rescript/darwin-arm64

npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/darwin-arm64@8129

@rescript/darwin-x64

npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/darwin-x64@8129

@rescript/linux-arm64

npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/linux-arm64@8129

@rescript/linux-x64

npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/linux-x64@8129

@rescript/runtime

npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/runtime@8129

@rescript/win32-x64

npm i https://pkg.pr.new/rescript-lang/rescript/@rescript/win32-x64@8129

commit: 72d5df0

@glennsl glennsl changed the title Strcter number parsing Stricter number parsing Dec 30, 2025
Comment on lines +61 to +65
let fromString: string => option<float> = %raw(`str => {
if (!str || !str.trim()) return;
let num = +str;
return isNaN(num) ? undefined : num;
}`)
Copy link

@CarlOlson CarlOlson Dec 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wrote some fast-check tests and couldn't find a difference between +str and Number(str), but the latter is easier to understand and could be written in pure ReScript.

How about converting this function to ReScript?

%%private(
  @val external makeNumber: 'a => float = "Number"
  @send external trim: string => string = "trim"
)
let fromString: string => option<float> = str =>
  if Js.typeof(str) === "string" && trim(str) !== "" {
    let num = makeNumber(str)
    isNaN(num) ? None : Some
  } else {
    None
  }

BTW just saw this, but I don't think the performance difference between +x and Number(x) should be a factor in this decision. However, my tests show the difference is nearly non-existent:

number-conversion

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's solely for performance, otherwise it should be equivalent. There might not be a noticeable difference when optimized anymore, but there are still situations where the might not be optimized and `Number would be significantly slower. If this is relevant here I'm not sure of though.

Another option is to just add a comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Int.fromString unexpected behavior

2 participants