0

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!

1
  • You need to format that number for output in the UI? Otherwise, 100 and 100.00 are equivalent. Commented Jun 20, 2018 at 15:19

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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'

Comments

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.