Reputation: 51
In my case I need to introduce a number in an input, and if the number I introduce in the input has a zero as decimal, for example 5.0 or 34.0, when I pass it to Number in TypeScript it saves it as 5 or 34.
But for the needs of a third party service, I need to pass a 5.0 of type number.
I have tried with parseFloat(stringValue).toFixed(1)
. This function returns a String with the value I need, but when I parse it to Number, it takes away the decimals.
For example:
let value = "5.0";
let fixedValue = parseFloat(value).toFixed(1); // Returns "5.0"
let numberValue = Number(fixedValue);
console.log(numberValue) // Returns 5
Has anyone been able to solve this or perform any similar functionality?
Upvotes: 4
Views: 3548
Reputation: 2663
In javascript there is no differentiation of integers and floats. All numbers are inherently floats. There is no difference between 1 and 1.0, they both shall be treated as equally.
To illustrate
1 === 1.0; //true;
parseInt(1) === parseFloat(1.0); //true;
parseFloat(1) === parseFloat(1.0); //true;
parseInt(1) === parseInt(1.0); //true;
The methods like .toFixed shall give a string representation. Ultimately whenever you convert, it would reduce the fraction part if its only 0.
Upvotes: 2
Reputation: 519
The fraction part of any decimal is usually reduced if it is .0. But your number still have its decimal capacity and if you need to show it, you have to use .toFixed(1) that will return string. anyway if your input need only to be showed in the template you can use that function to show its fraction part.
Upvotes: 0