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

fine-tuning of toNumber function #4684

Merged
merged 1 commit into from
Jan 12, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/shared/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export function _toString (val: any): string {
* If the conversion fails, return original string.
*/
export function toNumber (val: string): number | string {
const n = parseFloat(val, 10)
return (n || n === 0) ? n : val
const n = parseFloat(val)
return isNaN(n) ? val : n
Copy link
Member

@znck znck Jan 10, 2017

Choose a reason for hiding this comment

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

With regex

if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/.test(val))
      return Number(val);
return val;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

regex is also good…

Copy link
Member

Choose a reason for hiding this comment

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

I don't think using a regex is a good idea. parseFloat seems to be the fastest way to convert a string to a number: https://jsperf.com/number-vs-plus-vs-parsefloat

Copy link

Choose a reason for hiding this comment

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

what

}

/**
Expand Down