-2

I am trying to convert string to float in angular, but when I use parseFloat it is removing zero's from decimal. How can I keep these zero's with the values. Below example will help you to understand more

ex: My value is b="12.00" and I am trying to convert it to float using below syntax.

   abc = parseFloat(b.toFixed(2))

Current Output : 12

Expected Output : 12.00

Bhushan Khaladkar
  • 420
  • 1
  • 7
  • 20
  • This is how numbers work in JavaScript, unnecessary decimals are removed. But I really don't get why this is important to you. `12.00` and `12` are the same number, you can try `12 === 12.00`, it will return `true`. – JSON Derulo Jul 12 '23 at 07:07
  • 1
    If you want to keep the trailing zeroes for display purposes then you need to convert the number to a string and apply some formatting. If I said I had 12.00 apples you would understand that as I had exactly 12 apples - 12 and 12.00 are exactly the same number. A number does not have a format, that's what strings are for. – phuzi Jul 12 '23 at 07:10
  • Also, JavaScript only has a single [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) type used for all numbers. – phuzi Jul 12 '23 at 07:12
  • Does this answer your question? [How to check if a number has two decimal places and keep the trailing zero if necessary?](https://stackoverflow.com/questions/19192454/how-to-check-if-a-number-has-two-decimal-places-and-keep-the-trailing-zero-if-ne) – phuzi Jul 12 '23 at 07:14
  • @phuzi No, the url which you shared is not helpful for me – Bhushan Khaladkar Jul 12 '23 at 10:57

1 Answers1

1

This has nothing to do with Angular, what you code essentially does is this -

const b = "12.00";
const abc = parseFloat(b);

From Mozilla docs -

The toFixed() method formats a number using fixed-point notation.

This method returns a string with fixed-point notation. You have mentioned that you have the value "12.00" assigned to b, if this is a string value then you need to parse it before calling toFixed() like below -

const b = "12.00";
const parsedNum = Number.parseFloat("12.00");
const abc = parsedNum.toFixed(2); // This is essentially the same as the initial value of "b" i.e. "12.00", see if you really want to do this.

If it's a number, then just call the toFixed() like below -

const c = 12.00;
const abc = c.toFixed(2); // "12.00"

Also, go through this question.

Nakul Sharma
  • 419
  • 1
  • 4
  • 13