0

I am trying to use highcharts to make graphs. I currently have a string which I am looking to convert to a JSON array which looks like the following:

[{"chart":{"type":"line","renderTo":"chart_0"},"title":{"text":"Daily Sales & Spend"},
"xAxis":{"categories":["08-03-2015","08-04-2015"]},
"yAxis":{"title":{"text":"Dollars"}},
"series":[{"name":"Spend","data":[73.84,73.75]},{"name":"Sales","data":[1020.90,4007.90]}]}]

I need the trailing zeros so that 1020.90 stays 1020.90, on conversion the data becomes the following after the first index:

{"chart":{"type":"line","renderTo":"chart_0"},
"title":{"text":"Daily Sales & Spend"},
"xAxis":{"categories":["08-03-2015","08-04-2015"]},
"yAxis":{"title":{"text":"Dollars"}},
"series":[{"name":"Spend","data"[73.84,73.75]},{"name":"Sales","data":[1020.9,4009.9]}]}

The 1020.90 converts to 1020.9. I think this is a behavior of the float, but is it possible to convert it to 1020.90 [for display purposes]? I need this for displaying the data using highcharts.

applecrusher
  • 5,508
  • 5
  • 39
  • 89
  • 1
    internally, in most programming languages, trailing zero decimal places won't be represented. For display purposes, you might be able to use something like [toFixed()](http://stackoverflow.com/a/149099/32763) – Loopo Aug 18 '15 at 18:53
  • As Loopo says, this should help: `1020.9.toFixed(2)` will return `"1020.90"`. – Joseph Aug 18 '15 at 19:11
  • Please read the "Format Strings" section at this link - http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting – Mike Brant Aug 18 '15 at 19:12
  • Thanks everyone, Mike Brant, I was one that page and missed the demo. This is a good solution and I might implement it over the other. I ended up adding a 01 so it would be 1020.901 and then set tooltip valueDecimals to two decimal places. – applecrusher Aug 18 '15 at 20:52

1 Answers1

4

Prevent JSON.parse(data) from cutting off zero digit for String floats

This has nothing to do with JSON; this is about how numbers work in JavaScript

The 1020.90 converts to 1020.9

There is no "conversion" here. They're the same number.

I need this for displaying the data using highcharts

Then you need to pad the number with trailing zeros when you convert it to a string.

It is impossible to tell a float how many significant digits it has. You can only impose significant digits when you display the float as a string.

user229044
  • 232,980
  • 40
  • 330
  • 338