537

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

18 Answers 18

1146

You can use toFixed() to do that

var twoPlacedFloat = parseFloat(yourString).toFixed(2)
Sign up to request clarification or add additional context in comments.

7 Comments

toFixed is quite buggy though. Also, here's a better link than w3schools developer.mozilla.org/en-US/docs/JavaScript/Reference/…
but toFixed() returns number as string, if you will compare numbers, you need to use parseFloat again.
Use var twoPlacedFloat = + parseFloat(yourString).toFixed(2) to convert to float
Add parens to get a number instead of string: parseFloat((yourString).toFixed(2));
JavaScript does not have float data type by default. Check this developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures It has only number data type. So any attempt to covert number to floating value will actually converts number to string/number representation. So real life float value 2.00 is always string/number in javascript.
|
92

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

EDIT:

https://jsperf.app/kowulu

6 Comments

With above formula '2.00' returns 2. but I want it to be 2.00.
You can't have it both ways. If you want the output to be a number instead of a string, then you won't get trailing zeros. So you could use the above converted to a string: var twoPlacedFloat = (Math.round(2.002745 * 100) / 100).toFixed(2);
WIll the speed increase if I change 100's to 200's?
If the number of floating point operations stay the same the speed will be the same, so no
@ncubica It's about decimal place. If you take 100, then 2 digits after comma, if you take 10, then 1 digit after comma and so on.
|
60

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

5 Comments

I wrote a shopping cart program and tried using the toFixed() and the round() methods chained to the parseFloat() method. Neither of these methods worked with the parseFloat().
This saved me some to-be headaches. +1 just for that. I had no idea it would turn numbers to strings.
@Lukas Is not, if do parseFloat
This returns 2 if I apply to '2.00' number
This method is for corrections, not for formatting. For example: 0.1 + 0.2 // 0.30000000000000004 so I need correction for that (0.1+0.2).round() // 0.3
21

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

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

3 Comments

Are you missing something in your formula? var twoPlacedFloat = parseFloat(('2.00').toFixed(2)) generates error.
sorry, had a string variable instead of a number, which toFixed() needs - fixed now. But Rob's answer using Math.round is something to consider in terms of performance.
This should be a comment to Vlada's answer.
9

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

3 Comments

That not work as espected. parseFloat(parseFloat('10.5').toFixed(2)) return 10.5 espected 10.50. Also parseFloat(parseFloat('10.50').toFixed(2)) return 10.5
It's a float though, so 10.5 is equal to 10.50
I know that 10.5 == 10.50 but i need to print to client 10.50 not 10.5
8

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

1 Comment

Viable answer if using lodash, I'm currently using underscore.js and currently at 1.9.1 doesn't have a similar function.
8
parseFloat(parseFloat(amount).toFixed(2))

You have to parse it twice. The first time is to convert the string to a float, then fix it to two decimals (but the toFixed returns a string), and finally parse it again.

Comments

7

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

Exampale

let newValue = parseFloat(9.990000).toFixed(2)

//output
9.99

2 Comments

How can i do the reverse of this? I have 9.99 and want to get 9.990000
@Sofiyarao parseFloat('9.99').toFixed(6) and you will get 9.990000. toFixed determines how many digits are after the decimal
2

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

1 Comment

This returns a string, be careful
1

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    
}

1 Comment

Use this as following handles integer values as well function ParseFloat(str, val = 2) { str = str.toString(); if (str.indexOf(".") > 0) { str = str.slice(0, (str.indexOf(".")) + val + 1); } //Following is also an alternative if above does not work //str = str.match(/^-?\d+(?:\.\d{0,2})?/)[0]; return !isNaN(str) ? Number(str) : 0; }
0

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.

Comments

0

@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

1 Comment

To say there is no way to do it is completely dishonest. Long winded and complicated, sure, but not completely impossible - there are tons of working solutions on this stack alone.
0

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.

1 Comment

With commas is not working
0

TypeScript

/**
 * Convert a number or string to a float.
 * @param value Number or string.
 * @param precision Float precision.
 * @returns Float.
 */
function toFloat(value: number | string, precision: number = 2) {
  if (!value) return 0.0;
  if (typeof value === 'string') value = parseFloat(value);
  const p = Math.pow(10, precision);
  return Math.round(value * p) / p;
}

JavaScript

/**
 * Convert a number or string to a float.
 * @param {number | string} value Number or string.
 * @param {number} precision Float precision.
 * @returns {number} Float.
 */
function toFloat(value, precision = 2) {
  if (!value) return 0.0;
  if (typeof value === 'string') value = parseFloat(value);
  const p = Math.pow(10, precision);
  return Math.round(value * p) / p;
}

Comments

-3

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

Comments

-3
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;
  }

Comments

-5

I've got other solution.

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

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

4 Comments

@AustinHenley I tried using round() and it didn't work. That's probably why people are down voting. He may be refering to Math.round()
@Nathan it needs to be used inline, after parseFloat() as I've updated the answer by @zsalzbank
No, it doesn't work. You may try Math.round(parseFloat(yourString), 2);
Why not downvote an answer which will never work? There's simply no such method as round() on numbers in js. The real question is who upvoted this.
-5

The solution that work for me is the following

parseFloat(value)

1 Comment

This answer doesn't fix to 2 decimal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.