TSR TSR - 1 month ago 16
Javascript Question

Converting String currency

How can I convert numbers from a string, and return the same format?

//INPUT as STRING
var dollar1 = "US $59.99 - 69.99 / piece"
var dollar2 = "US $237.50 - 277.50 /lot"
var US_to_MUR_rate = 35;
//FUNCTION
function convert ( string, rate) {
//what should be here ?

return str_converted;
}

//EXPECTED OUPUT as STRING:
var ruppes1 = convert (dollar1, US_to_MUR_rate);
var ruppes2 = convert (dollar2, US_to_MUR_rate);
console.log(rupees1);
"MUR Rs2099.65 - 2449.65 / piece"
console.log(rupees2);
"MUR Rs8032.5 - 9712.5 /lot"

Answer

//INPUT as STRING
var dollar1 = "US $59.99 - 69.99 / piece"
var dollar2 = "US $237.50 - 277.50 /lot"
var US_to_MUR_rate = 35;

//FUNCTION
function convert ( string, rate) {
  return string
    .replace(/\d+\.\d+/g, function(match) {
      return (parseFloat(match) * US_to_MUR_rate).toFixed(2);
    })
    .replace(/US \$/, 'MUR Rs');
}

//EXPECTED OUPUT as STRING:
var rupees1 = convert (dollar1, US_to_MUR_rate);
var rupees2 = convert (dollar2, US_to_MUR_rate);

console.log(rupees1);
console.log(rupees2);