• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

196
Views
How to convert an array of strings into a number?

I'm fetching data from an API which returns currency exchange rates like so:

{"EUR_USD":1.044136}

I was able to manipulate the fetched data using:

const rate = Object.values(data).splice(11,5);

which returns 1.044

However, my next problem comes when trying to parseFloat this object into a number.. for some reason it only returns the first digit so in case of "1.044" it'd convert it into "1".

How can I handle this ? I'm thinking to perhaps map thru the rate array and then parseFloat everything..?

const parsedRate = rate.map(i => i).parseFloat(); would this even work ?

ok guys - sorry for taking your time and I appreciate all your answers! but I had JSON.stringify on the string and that's what was causing the problem... SORRY!!!

almost 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

array.map(Number) would return an array of whatever is being mapped converted to number (assuming its possible)

almost 3 years ago · Juan Pablo Isaza Report

0

I think you have problem with different length of keys. You have to use Object.values

const data = [{"EUR_NOUSD":"1.044136"}, {"EUR_EURO":"1.15"},{"EUR_CANDIES":"2.333"}]

const getValue = currency => Number(Object.values(currency))

console.log(data.map(getValue))

almost 3 years ago · Juan Pablo Isaza Report

0

The example data you have supplied is an plain old Javascript object literal:

{"EUR_USD":1.044136}

You just need to access the exchange rate(s) by their name. Assuming it's in a variable called rates, it's just

const rate = rates.EUR_USD;

to assign the numeric value 1.044136 to the variable rate.

If, however, you have a string containing the JSON response from the API:

"{\"EUR_USD\":1.044136}"

And you're trying to use string.splice() to extract bits from it, you are going about it the wrong way.

All you have to do to rehydrate that JSON response body into an object is to use JSON.parse():

const json = callUpstreamExchangeRateApi();
const rates = JSON.parse(json);
const rate  = rates.EUR_USD;
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error