2

I have this code (@Model.TW is 11,58 and @Model.TK is 27,65)(both doubles):

var parameters = [@Model.TW,@Model.TK];

When checking parameters[0] and [1] the double values are rounded to 11 and 27. Why is this?

The same happens when just doing

var double = [@Model.TW];

or

var double = parseFloat('[@Model.TW]');

even if the return types of @Model.xx are changed to string there is no difference.

ManyQuestions
  • 1,069
  • 1
  • 16
  • 34
  • Try `[parseDouble('@Model.TW')]` - probably parsing as an int – tymeJV May 06 '15 at 19:40
  • is it because the browser is using a different culture? If I use `[11.58, 27.65]`, it works for me using standard en-US OS settings. Is yours going to 4 values: `[11, 58, 27, 65]` ? – ps2goat May 06 '15 at 19:43
  • tried parsefloat, no results. @ps2goat No the value order is fine, the values just get rounded to ints. – ManyQuestions May 06 '15 at 19:49

1 Answers1

2

Float values passed to JavaScript as JSON or direct values must have "." as decimal separator. Some cultures use "," and thus parsing of such numbers as JSON or with parseFloat will fail to recognize decimal part.

Fix: use invariant culture to format numbers or use existing libraries (like Json.Net) to produce JSON.

var parameters = [@(Model.TW.ToString(CultureInfo.InvariantCulture)),
     @(Model.TK.ToString(CultureInfo.InvariantCulture))];

JSON sample can be found at - How do I write unencoded Json to my View using Razor?

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179