Skip to content Skip to sidebar Skip to footer

How To Get A Float Using Parsefloat(0.00)

How can I get a float of 0.00. The reason I need 0.00, is because I am going to be accumalating float values by adding. Hence starting with 0.00. I tried var tmp ='0.00' tmp = p

Solution 1:

You can use the string tmp variable and then when you need to add to it use:

tmp = (+tmp + 8).toFixed(2);

JSFIDDLE DEMO

Or simply write a function to do that seeing that you'll have to do that many times:

function strAdd( tmp, num ) {
    return (+tmp + num).toFixed(2);
}

Solution 2:

There is no such thing as an integer type in javascript. There is only Number, which is stored as a double precision floating point. So to get a floating point value with 0.00, you need only to do this:

var tmp = 0;

Solution 3:

var tmp ='0.00'
tmp  = parseFloat(tmp.toString()).toFixed(2);
totals=parseFloat(tmp).toFixed(2);
alert(totals); //0.00

parseFloat() without toFixed() removes zeros after dot. So you need to add toFixed() again.

Solution 4:

Here is dynamic floatParser for those who need

functioncustomParseFloat(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;
      }
    })

    returnparseFloat(str).toFixed(toFixedLength);
  }

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

Solution 5:

You can use parseFloat function in Javascript.

<buttononclick="myFunction()">Try it</button><pid="demo"></p><script>functionmyFunction() {
    var a = parseFloat("10") + "<br>";
    var b = parseFloat("10.00") + "<br>";
    var c = parseFloat("10.33") + "<br>";
    var d = parseFloat("34 45 66") + "<br>";
    var e = parseFloat("   60   ") + "<br>";
    var f = parseFloat("40 years") + "<br>";
    var g = parseFloat("He was 40") + "<br>";

    var n = a + b + c + d + e + f + g;
    document.getElementById("demo").innerHTML = n;
}
</script>

Post a Comment for "How To Get A Float Using Parsefloat(0.00)"