How do I stop parseFloat() from stripping zeroes to right of decimal

后端 未结 5 980
长情又很酷
长情又很酷 2020-12-05 14:12

I have a function that I\'m using to remove unwanted characters (defined as currency symbols) from strings then return the value as a number. When returning the value, I am

5条回答
  •  借酒劲吻你
    2020-12-05 14:56

    For future readers, I had this issue as I wanted to parse the onChange value of a textField into a float, so as the user typed I could update my model.

    The problem was with the decimal place and values such as 12.120 would be parsed as 12.12 so the user could never enter a value like 12.1201.

    The way I solved it was to check to see if the STRING value contained a decimal place and then split the string at that decimal and then count the number of characters after the place and then format the float with that specific number of places.

    To illustrate:

    const hasDecimal = event.target.value.includes(".");
    const decimalValue = (hasDecimal ? event.target.value.split(".") : [event.target.value, ""])[1];
    const parsed = parseFloat(event.target.value).toFixed(decimalValue.length);
    const value = isNaN(parsed) ? "" : parsed;
    onEditValue(value);
    

提交回复
热议问题