How to parse float with two decimal places in javascript?

前端 未结 16 1610
春和景丽
春和景丽 2020-11-27 08:55

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

相关标签:
16条回答
  • 2020-11-27 09:51
    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;
      }
    
    0 讨论(0)
  • 2020-11-27 09:54

    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);
    }
    
    0 讨论(0)
  • 2020-11-27 09:55

    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

    0 讨论(0)
  • 2020-11-27 09:59

    I've got other solution.

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

    var twoPlacedFloat = parseFloat(yourString).round(2)
    
    0 讨论(0)
提交回复
热议问题