How do I stop parseFloat() from stripping zeroes t

2019-01-18 03:11发布

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 making the following call:

return parseFloat(x);

The problem I have is that when x == "0.00" I expect to get 0.00 (a float with two decimals) back. What I get instead is simply 0.

I've also tried the following:

return parseFloat(x).toFixed(2);

and still get simply 0 back. Am I missing something? Any help would be greatly appreciated.

Thank you!!

4条回答
爷的心禁止访问
2楼-- · 2019-01-18 03:55

this should work:

return parseFloat(x).toFixed(2);

you can test it by running this in firebug:

var x = '0.00';
alert(parseFloat(x).toFixed(2));
查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-18 03:59

simple:

function decimalPlaces(float,length) {
  ret = "";
  str = float.toString();
  array = str.split(".");
  if(array.length==2) {
     ret += array[0] + ".";
     for(i=0;i<length;i++) {
        if(i>=array[1].length) ret += '0';
        else ret+= array[1][i];
     }
  }
  else if(array.length == 1) {
    ret += array[0] + ".";
    for(i=0;i<length;i++) {
       ret += '0'
    }
  }

  return ret;
}

document.write(decimalPlaces(3.123,6));
查看更多
聊天终结者
4楼-- · 2019-01-18 04:08

parseFloat() turns a string into a floating point number. This is a binary value, not a decimal representation, so the concept of the number of zeros to the right of the decimal point doesn't even apply; it all depends on how it is formatted back into a string. Regarding toFixed, I'd suggest converting the floating point number to a Number:

new Number(parseFloat(x)).toFixed(2);
查看更多
我命由我不由天
5楼-- · 2019-01-18 04:09

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);
查看更多
登录 后发表回答