Chris K.
Chris K.

Reputation: 752

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

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!!

Upvotes: 34

Views: 62590

Answers (5)

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;
}
console.log(decimalPlaces(3.123, 6));

Upvotes: 4

Sagynbek Kenzhebaev
Sagynbek Kenzhebaev

Reputation: 360

Here is dynamic version of floatParser for those who need

function customParseFloat(number){
  if(isNaN(parseFloat(number)) === false){
    let toFixedLength = 0;
    let str = String(number);

    // You may add/remove seperator according to your needs
    [".", ","].forEach(seperator=>{
      let arr = str.split(seperator);
      if( arr.length === 2 ){
        toFixedLength = arr[1].length;
      }
    })

    return parseFloat(str).toFixed(toFixedLength);
  }

  return number; // Not a number, so you may throw exception or return number itself
}

Upvotes: 1

Rob Sanders
Rob Sanders

Reputation: 5387

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);

Upvotes: 3

Ted Hopp
Ted Hopp

Reputation: 234857

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);

Upvotes: 25

Victor
Victor

Reputation: 4721

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));

Upvotes: 13

Related Questions