0

I was trying to implement a form which has a text box that accepts an input from user and converts it to double for sending post request. Example as below.

Image 1

The issue is the input from user is in string format, so I am doing something like, whenever that is onChange then convert it to val/100 and save as double in the state and when displaying on UI display as val*100.All the Values as being displayed correctly but only problem is with Value 7, which overflows to 7.00000001, I am not able to figure out why does it happens. Inside debugger the Value is showing 0.07 and 7 only. See below for the Error.

Error Facing

<TextBox 
   value={getConvertedValue()}
   onChange={changeHandler}   
/>

function getConvertedValue() {
    return (MobxObservable * 100).toString; 
}

changeHandler(event: React.FormEvent, val: string) => {
   // apAction function that sets the value in store.
   setValue(Number(val)/100);
}

Problem - I cannot use Math.round since user wants to enter 1.25 also, toFixed() cannot be used as entering 3 would be then displayed as 3.00 which I doesn't wanted.

What can be the possible solution for this. Tried with available methods but didn't work.

  • https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – epascarello Jul 01 '22 at 16:16
  • 1
    you need some kind of limit in your precision after all – Psi Jul 01 '22 at 16:22
  • [Please replace/supplement images of code/errors with plaintext versions.](https://meta.stackoverflow.com/a/285557/2887218) – jcalz Jul 01 '22 at 16:25

1 Answers1

0

Can't really find a fix to that, but here's a small hack, try mulitply it by 1000 then devide by 10:

return ((val * 1000)/10).toString();
Fakhri
  • 49
  • 4