Mritunjay Upadhyay
Mritunjay Upadhyay

Reputation: 1094

How to convert string currency value in integer

I have string like "17,420 ฿". How to change this as integer value. I have done

var a = "17,420 ฿"
var b = a.split(' ')[0];
console.log(Number(b))

But I am getting NaN because of ,. So i have done like below

var c = b.replace( /,/g, "" );
console.log(Number(c));

Now, I am getting 17420 as an integer.

But, is there any better method to do it.

Upvotes: 1

Views: 787

Answers (5)

kockburn
kockburn

Reputation: 17616

Split for the , and then join via . and then parse it as a float. Use .toFixed() to determine how many decimal places you wish to have.

console.log(
  parseFloat("17,420 ฿".split(' ')[0].split(',').join('.')).toFixed(3)
);

As a function:

const convert = (str) => {
  return parseFloat(str.split(' ')[0].split(',').join('.')).toFixed(3)
}

console.log(convert("17.1234 $"));
console.log(convert("17 $"));
console.log(convert("17,2345 $"));

Alternative:

const convert = (str) => {
  let fixedTo = 0;
  const temp = str.split(' ')[0].split(',');
  if(temp.length > 1){
    fixedTo = temp[1].length;
  }

  return parseFloat(temp.join('.')).toFixed(fixedTo)
}

console.log(convert("17,1234 $"));
console.log(convert("17,123 $"));
console.log(convert("17,1 $"));
console.log(convert("17 $"));

Upvotes: 1

HelgeFox
HelgeFox

Reputation: 349

You can easily remove all non-digits with a regex like so:

a.replace(/\D/g, '');

Then use parseInt to get integer value:

parseInt(b);

Combined:

var result = parseInt(a.replace(/\D/g, ''));

Upvotes: 2

Daniel Furutani
Daniel Furutani

Reputation: 11

Number(a.replace(/[^0-9.]/g, ""))

This will replace all not numbers chars... is that helpful?

Upvotes: 1

Sruthi
Sruthi

Reputation: 3018

You can use parseInt after removing the comma

var a = "17,420 ฿"
console.log(parseInt(a.replace(",",""), 10))

o/p -> 17420

Upvotes: 1

Joseph
Joseph

Reputation: 119837

You could start by stripping off anything that's NOT a number or a decimal point. string.replace and a bit of RegExp will help. Then use parseFloat or Number to convert that number-like string into a number. Don't convert to an integer (a decimal-less number), since you're dealing with what appears to be currency.

const num = parseFloat(str.replace(/[^0-9.]/g, ''))

But then at the end of the day, you should NOT be doing string-to-number conversion. Store the number as a number, then format it to a string for display, NOT the other way around.

Upvotes: 5

Related Questions