-2

I want to convert string to Int or float type in JavaScript below is my code. or any solution is there in react library?

var a = '23,34.0';
console.log(parseFloat(a)); // 23
console.log(parseInt(a)) // 23

I want output like this: `var a = '23,34.0';

output :

23,34.0    as a integer

I tried below codes

parseInt(a) parseFloat(a) Number(a) this methods I tried but am not exact outputs.

adiga
  • 34,372
  • 9
  • 61
  • 83
Mohamed
  • 13
  • 3
  • Try `Number(a.replace(/[^\.\d]/g, ''))` – User863 Jan 17 '23 at 06:55
  • What is the expected output? `23,34.0` neither has `,` as thousands separator nor decimal. Is it 2 numbers separated by a comma? – adiga Jan 17 '23 at 06:58
  • The string you are passing contains comma as well while parseInt and parseFloat do not accept that format. what you can do is to remove the comma from your string first and then use parseInt or parseFloat. Something like parseInt(a.replace(',','')); – Hannan Ayub Jan 17 '23 at 06:59
  • The string value came from input may be user will type comma or decimal that part I want to convert Int. user type '22,45' like this or '22.34' like this. based on the user system generic settings. – Mohamed Jan 17 '23 at 11:52

1 Answers1

-1

Since your string is not a valid number, you cannot convert it.

You have to pass a valid number like 2324.5 to convert.

Trying this

var a = '2334.5'
console.log(parseFloat(a))
console.log(parseInt(a))

You will get 2334.5 and 2334 as output. "parseInt" will still yet cut of everything after the decimal point, because that's what an integer is, a whole number.

  • The string value came from input may be user will type comma or decimal that part I want to convert Int. user type '22,45' like this or '22.34' like this. based on the user system generic settings. please let me know '22,34' if string contains comma how to convert number? – Mohamed Jan 17 '23 at 11:55