How to parse float with two decimal places in javascript?

JavascriptFloating Point

Javascript Problem Overview


I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00. Or if it equals 10.6 would be 10.60. Not sure how to do this.

price_result = parseFloat(test_var.split('$')[1].slice(0,-1));

Javascript Solutions


Solution 1 - Javascript

You can use toFixed() to do that

var twoPlacedFloat = parseFloat(yourString).toFixed(2)

Solution 2 - Javascript

If you need performance (like in games):

Math.round(number * 100) / 100

It's about 100 times as fast as parseFloat(number.toFixed(2))

http://jsperf.com/parsefloat-tofixed-vs-math-round

Solution 3 - Javascript

When you use toFixed, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.

Number.prototype.round = function(p) {
  p = p || 10;
  return parseFloat( this.toFixed(p) );
};

and use:

var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143

or simply:

(22/7).round(3); // 3.143

Solution 4 - Javascript

To return a number, add another layer of parentheses. Keeps it clean.

var twoPlacedFloat = parseFloat((10.02745).toFixed(2));

Solution 5 - Javascript

If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:

function parseFloat2Decimals(value) {
    return parseFloat(parseFloat(value).toFixed(2));
}

function parseFloat2Decimals(value,decimalPlaces) {
    return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}

Solution 6 - Javascript

ceil from lodash is probably the best

_.ceil("315.9250488",2) 
_.ceil(315.9250488,2) 
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)

will work also with a number and it's safe

Solution 7 - Javascript

You can use .toFixed() to for float value 2 digits

Exampale

> let newValue = parseFloat(9.990000).toFixed(2) >
> //output > 9.99

Solution 8 - Javascript

Please use below function if you don't want to round off.

function ConvertToDecimal(num) {
    num = num.toString(); //If it's not already a String
    num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
   alert('M : ' +  Number(num)); //If you need it back as a Number    
}

Solution 9 - Javascript

I have tried this for my case and it'll work fine.

var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);

Sample output:

> 9.007

Solution 10 - Javascript

For what its worth: A decimal number, is a decimal number, you either round it to some other value or not. Internally, it will approximate a decimal fraction according to the rule of floating point arthmetic and handling. It stays a decimal number (floating point, in JS a double) internally, no matter how you many digits you want to display it with.

To present it for display, you can choose the precision of the display to whatever you want by string conversion. Presentation is a display issue, not a storage thing.

Solution 11 - Javascript

@sd Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.

Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options

  1. Either use data as a string or
  2. Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5. Number Cannot have trailing zeros after decimal

Solution 12 - Javascript

You can store your price as a string

You can use Number(string)

for your calculations.

example

Number("34.50") == 34.5

also

Number("35.65") == 35.65

If you're comfortable with the Number function , you can go with it.

Solution 13 - Javascript

Try this (see comments in code):

function fixInteger(el) {
    // this is element's value selector, you should use your own
    value = $(el).val();
    if (value == '') {
        value = 0;
    }
    newValue = parseInt(value);
    // if new value is Nan (when input is a string with no integers in it)
    if (isNaN(newValue)) {
        value = 0;
        newValue = parseInt(value);
    }
    // apply new value to element
    $(el).val(newValue);
}

function fixPrice(el) {
    // this is element's value selector, you should use your own
    value = $(el).val();
    if (value == '') {
        value = 0;
    }
    newValue = parseFloat(value.replace(',', '.')).toFixed(2);
    // if new value is Nan (when input is a string with no integers in it)
    if (isNaN(newValue)) {
        value = 0;
        newValue = parseFloat(value).toFixed(2);
    }
    // apply new value to element
    $(el).val(newValue);
}

Solution 14 - Javascript

Simple JavaScript, string to float:

var it_price = chief_double($("#ContentPlaceHolder1_txt_it_price").val());

function chief_double(num){
    var n = parseFloat(num);
    if (isNaN(n)) {
        return "0";
    }
    else {
        return parseFloat(num);
    }
}

Solution 15 - Javascript

Solution for FormArray controllers 

Initialize FormArray form Builder

  formInitilize() {
    this.Form = this._formBuilder.group({
      formArray: this._formBuilder.array([this.createForm()])
    });
  }

Create Form

  createForm() {
    return (this.Form = this._formBuilder.group({
      convertodecimal: ['']
    }));
  }

Set Form Values into Form Controller

  setFormvalues() {
    this.Form.setControl('formArray', this._formBuilder.array([]));
    const control = <FormArray>this.resourceBalanceForm.controls['formArray'];
    this.ListArrayValues.forEach((x) => {
      control.push(this.buildForm(x));
    });
  }

  private buildForm(x): FormGroup {
    const bindvalues= this._formBuilder.group({
      convertodecimal: x.ArrayCollection1? parseFloat(x.ArrayCollection1[0].name).toFixed(2) : '' // Option for array collection
// convertodecimal: x.number.toFixed(2)    --- option for two decimal value 
    });

    return bindvalues;
  }

Solution 16 - Javascript

I've got other solution.

You can use round() to do that instead toFixed()

var twoPlacedFloat = parseFloat(yourString).round(2)

Solution 17 - Javascript

The solution that work for me is the following

parseFloat(value)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser357034View Question on Stackoverflow
Solution 1 - JavascriptMahesh VelagaView Answer on Stackoverflow
Solution 2 - JavascriptRob BoermanView Answer on Stackoverflow
Solution 3 - JavascriptVladaView Answer on Stackoverflow
Solution 4 - JavascriptpvanallenView Answer on Stackoverflow
Solution 5 - JavascriptSavageView Answer on Stackoverflow
Solution 6 - JavascriptAntonio TerrenoView Answer on Stackoverflow
Solution 7 - JavascriptRizwanView Answer on Stackoverflow
Solution 8 - JavascriptNimeshView Answer on Stackoverflow
Solution 9 - JavascriptHabib_95View Answer on Stackoverflow
Solution 10 - JavascriptandoraView Answer on Stackoverflow
Solution 11 - Javascriptabhinav pandeyView Answer on Stackoverflow
Solution 12 - JavascriptroqkabelView Answer on Stackoverflow
Solution 13 - JavascriptMitre SlavchevView Answer on Stackoverflow
Solution 14 - JavascriptArun Prasad E SView Answer on Stackoverflow
Solution 15 - JavascriptThulasiram VirupakshiView Answer on Stackoverflow
Solution 16 - Javascriptequipo_INSA-Inditex_OUView Answer on Stackoverflow
Solution 17 - JavascriptJorge Santos NeillView Answer on Stackoverflow