Andrew Mamontov
Andrew Mamontov

Reputation: 43

Float in Ruby on Rails Json

I faced a big problem: I have an API method, that returns JSON.

One of fields has property float and I need it to be 5.0. But when I convert it to JSON it becomes 5.

Even if I make this thing render :json => 5.to_f it returns me integer anyway. What do I need to do to have 5.0 in JSON response? Many Thanks

Upvotes: 2

Views: 3265

Answers (3)

z.shan
z.shan

Reputation: 339

All numbers are floats in Javascript. Numbers are "double-precision 64-bit format IEEE 754 values". if you want to do then you should have to do like this when we render json there is no floating points >0 that's why it is showing as integer you can convert it to string value to do this like

 render json: 5.to_f.to_s

only if integer value is in object field then it will show as float

Upvotes: 0

dvxam
dvxam

Reputation: 604

All numbers are floats in Javascript. Numbers are "double-precision 64-bit format IEEE 754 values".

see ECMAScript 2015 Language Specification.

What it means, is that, 5.0 and 5 are the same in JS. There is no differentiation of int, float or double. As JSON (which stand for JavaScript Object Notation) generally end up as a JS object, 5 represents a float. Since JSON format is mostly used for data transfert/communication purpose, the decision to omit the the decimal part must be to save a few bytes in the string that is passed around.

In @z.shan's answer, the 5.0 is passed as a string "5.0". Depending on what you want, I would recommend to keep the 5 as a number in the JSON payload.

Upvotes: 4

Or you can use conversion like that :

integer = 5
render json: ('%.2f'%integer)

Upvotes: 0

Related Questions