1

I am sending an js object to Django backend:

  {
    name: "somename", 
    mynumber:Number('.1')
  }

In Django backend i have an array:

  arr = [Decimal(".1"),Decimal("1"),Decimal('2'),.....]

When i get an integer type number from mynumber front end, python recognizes the number. But when i send an float type number such as Number('.1') or Number('.2'), this number i cannot compare with python Decimal('.1') or Decimal('.2').

How can i send the front end number so that i can compare the number with Decimal('.1') or Decimal('.2')?

Rui Costa
  • 417
  • 2
  • 11
Aurora
  • 133
  • 11
  • 4
    Did you try just sending as a string and converting to Decimal on the python side? – getup8 Jul 03 '21 at 15:54
  • yes i did. it works. but i dont want to change backend code. i was wondering if there is a way to send data such that i dont have to change the backend. – Aurora Jul 03 '21 at 15:57
  • 1
    did you try `{ ... , mynumber: .1, ...}` ? – Mister Jojo Jul 03 '21 at 15:58
  • yes i did. it does not work. i guess python Decimal() works differently than Number(). i also tried parseFloat(".1") from js. same result. it does not recognized by pythonas .1 – Aurora Jul 03 '21 at 16:02
  • 1
    BTW, pay attention to the fact that .1 is a decimal number (i.e., in radix 10), but **not** the exact value of a float (i.e., a floating-point number in radix 2), so in JavaScript you'll get, for example, `.1 + .1 + .1 === .3` → `false`, because of the error for rounding `".1"` (while in Python, `Decimal(".1") + Decimal(".1") + Decimal(".1") == Decimal(".3")` → `True`) – ErikMD Jul 03 '21 at 16:12
  • 1
    So @getup8's suggestion to keep your decimal literals as "strings" as long as possible (before parsing them as proper `Decimal` numbers) certainly seems the way to go in your use case… – ErikMD Jul 03 '21 at 16:12
  • 1
    Note however that there are dedicated Decimal libraries for JavaScript that you might want to use: see e.g. this SO answer [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/a/27251971/9164010). – ErikMD Jul 03 '21 at 16:18
  • 1
    @Aurora in order to understand better, why on the Back-end, are you using Decimal(str) and not just a float? any particular reason? – Federico Baù Jul 03 '21 at 16:24
  • 1
    after doing some research i decided that i will make change in the backend file as Decimal(object.mynumber) rather changing in the frontend for my case. – Aurora Jul 05 '21 at 12:19

1 Answers1

0

after doing some investigation on my project i decided that i will change in the backend file as Decimal(object.mynumber) rather changing in the frontend. In this case i have to make changes in multiple places. But as i think it is better to send backend data as string.

Aurora
  • 133
  • 11