What I’m trying to do:
I’m sending floating number from the server side to the client side and then doing some string formatting on the client.
What I’ve tried and what’s not working:
I’m doing a simple str
on the client side of number 82151.1
and is in incorrectly being converted into string “82151.10000000001”.
Same code on the server side works as expected an returns “82151.1”.
There are multiple possible workarounds:
- Converting to string on the server side
- Specify precision on the conversion f’{number:.2}’
But this is still be problematic.
Code Sample:
self.label_1.text = str(82151.1)
The number itself doesn’t seem to be the problem, since multiplying it by 10^10 and converting it to a string doesn’t show that last 1.
Clone link:
https://anvil.works/build#clone:DQKUNMABVS2YYGR6=ANJDNEK7U2FAKDF2N5SQYS3T
Hi @gorka.eguileor
I think this is a bug even though I see many posts on stackoverflow concerning conversion from float to string.
While I leave the most exhaustive answer to some expert, I can suggest another way to have the conversion done without disturbing the server.
You can leverage Javascript conversion function, which results to be more precise in this case.
Create a small something-to-string conversion function in your Native Libraries, like
<script>
function js_str(num){
return num.toString();
}
</script>
Then in your python code:
def js_str(self,num):
return self.call_js('js_str',num)
and now
number_str = self.js_str(number)
#or directly number_str = self.call_js('js_str',number) removing the need for the python wrapper function
self.label_1.text = f"Client code string conversion changes 82151.1 into {number_str}"
prints the correct value.
It’s not exactly a bug - it’s a difference in precision for the str representation of the same number.
You can try doing the following on the server and client
format(86721.1, '.16g') # 16 significant figures
format(86721.1, '.15g')
You’ll likely get the 82151.10000000001
for 16g
but not for 15g
.
It’s the problem of floating point arithmetic from the python docs
I’d suggest going with a format str approach to display floating point numbers.
(which you already mentioned)
format(82151.1, '.2')
f'{82151.1: .2}'
Worth noting that, although the javascript work around works in this case.
It doesn’t work in general. e.g.
x = .1 + .1 + .1
# 0.30000000000000004
So i wouldn’t recommend that approach.
4 Likes
Thanks for the reply. Even if I prefer using f-strings or format
method providing explicit precision, your reply was very illustrative, since I’m new to Anvil and I didn’t know of the call_js
method. 
Thanks for the detailed explanation, it was really helpful.
Nothing like being explicit when doing string formatting to avoid issues. 
1 Like