Recharts: Question: Converting string values to number for line chart

Created on 22 Mar 2017  路  3Comments  路  Source: recharts/recharts

Is it possible to convert a string to a number for a line chart? I am creating a number of line charts for a reporting tool. Some of the values are numbers and those work great, but others are strings that are actually numbers. Being able to call parseInt() or parseFloat() on the strings would be enough for my use, I'm just not finding an acceptable place to do so. Any thoughts?

Using recharts v0.21.2 on Mac OS Sierra with Chrome 56.0.2924.87

Most helpful comment

This is a little inconvenient to me as well. But I do understand the downside of doing it inside Recharts.

In many projects, I got various kind of numbers in string format from server-side, like "99.7", "$12.4", "2,345,678", etc. Let's assume that Recharts uses new Number(value) to parse these strings, it will return a lot of NaN, which is unexpected to users.

An option is to leverage Numbro lib to parse those number-like strings: http://numbrojs.com/format.html#unformat . The parsing result looks good, but it's still not a good idea to make Numbro a direct dependency of Recharts.

I have another idea, what about adding a new prop dataConverter along with existing dataKey? Something like this:

<Line dataKey="price" dataConvertor={value => numbro().unformat(value)} />

All 3 comments

@jshamley It's recommended to call parseInt() or parseFloat before passing to recharts.

This is a little inconvenient to me as well. But I do understand the downside of doing it inside Recharts.

In many projects, I got various kind of numbers in string format from server-side, like "99.7", "$12.4", "2,345,678", etc. Let's assume that Recharts uses new Number(value) to parse these strings, it will return a lot of NaN, which is unexpected to users.

An option is to leverage Numbro lib to parse those number-like strings: http://numbrojs.com/format.html#unformat . The parsing result looks good, but it's still not a good idea to make Numbro a direct dependency of Recharts.

I have another idea, what about adding a new prop dataConverter along with existing dataKey? Something like this:

<Line dataKey="price" dataConvertor={value => numbro().unformat(value)} />

+1 for dataConverter prop idea, would mitigate the need (in many cases) to mutate data sets before passing to recharts components.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sdoomz picture sdoomz  路  3Comments

sortsen picture sortsen  路  3Comments

YikaJ picture YikaJ  路  3Comments

alexandersoto picture alexandersoto  路  3Comments

p2227 picture p2227  路  3Comments