Reputation: 227
I'm new to writing JavaScript, I'm trying to convert two values from a string to a number, however, I have tried to doing the following approaches but none seem to work. Example:
const num = parseInt('100.00') // returns 100
const num = Number('100.00') // returns 100
const num = +'100.00'; // returns 100
I need to return 100.00 as a number I have gone to other similar post they didn't seem to help, all knowledge is appreciated thanks!
Upvotes: 0
Views: 621
Reputation: 72186
It seems to me that all the approaches you have tried work.
Internally, JavaScript stores all numbers using the floating point format. It uses the minimum number of decimals needed when it displays the value.
This is 0
for integer numbers as 100
. 100.00
is still 100
, adding any number of 0
after the decimal point doesn't change its value.
The recommended method to parse a string that looks like a number is to use Number.parseInt()
or Number.parseFloat()
.
parseFloat()
recognizes only numbers written in base 10
but parseInt()
attempts to detect the base by analyzing the first characters of the input string. It automatically recognizes numbers written in bases 2
, 8
, 10
and 16
using the rules described in the documentation page about numbers. This is why it's recommended to always pass the second argument to parseInt()
to avoid any ambiguity.
Regarding your concern, use Number.toFixed()
to force its representation using a certain number of decimal digits, even when the trailing digits are 0
:
const num = parseInt('100.00');
console.log(num); // prints '100'
console.log(num.toFixed(2)); // prints '100.00'
Upvotes: 1
Reputation: 1305
What you are asking is not possible, the decimal 100 is not representable as 100.00 as number, you can only represent it as a String with help of toFixed
;
var num = 100;
var strNum = num.toFixed(2); // in this case you have a string instead of a number
console.log(typeof num, num);
console.log(typeof strNum, strNum);
Upvotes: 1
Reputation: 23029
In Javascript everything is Number, which is double-precision floating point 64 bit number (=decimal).
100.00 is equal to 100, therefore it shows you 100.
Upvotes: 1