Is there any way to go from a float 1.0 to 1.00 while retaining the float() type?
You will need something that will format your floats. The Number library does this.
According to the spec that will convert the float to a string
Floats are not actually stored as 1.0 and so on, they have a different internal representation.
Can you explain what it is you’re trying to accomplish?
Correct. When you format, you convert to string.
(Sorry, I missed the “while retaining the float type” part).
I am sending in a value into an API and saw the decimal value coming back as 1.0 instead of 1.00. It causes a breaking error with the API so I was going to confirm that if sending in 1.00 still breaks that would be an API issue i’d assume.
Is that a json api? If so you’d need to look into your json libraries encoding function. But in the end if you’re not formatting as a string there’s likely no difference. Unless the other end parses the float number back into a decimal, but again into a float value it’ll always become 1.0. Floats do not explicitly store decimal points and when the binary float format is converted to a string for inspection it’s just printed with the least amout of decimal points.
Okay, so the actual question is “how do I get the JSON encoder to format floats with extra precision”. We don’t know what JSON library you’re using, but the Erlang :json just calls float_to_binary. It looks like the encoder function can be overridden, so you could provide one that encodes floats with extra zeros if you like.
However, as suggested above this is probably a waste of time. The consumer of the API should just decode the value back into a float, in which case it won’t matter. But if you have some weird requirement for this behavior, that’s how you would do it.
It’s also worth remembering that JSON doesn’t have an integer or float type, only numbers. Different JSON libraries handle numbers in different ways. For example, golang treats all JSON numbers as floats by default (even when the number doesn’t have a decimal point). So, it’s undefined what will happen to precision when you send a number over JSON.
It treats all numbers based on the type of the target field in the struct you deserialise into.
Sorry for the delayed responses but turns out the API we were using breaks when you pass in 2.00 instead of 2 but 2.01 is completely acceptable. It just breaks when it is 2.0 or 2.00.
So would this not help you?
def api_friendly_float(num) when is float(num) do
truncated = trunc(num)
if num == truncated, do: truncated, else: num
end
Then you use the function when you serialise number and that should be all?






















