转换字符串货币

时间:2016-10-26 06:32:57

标签: javascript jquery string numbers

如何从字符串转换数字,并返回相同的格式?

//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"

2 个答案:

答案 0 :(得分:1)

//INPUT as STRING
var dollar1 = "US $59.99 - 69.99 / piece"
var dollar2 = "US $237.50 - 277.50 / lot"
var dollar3 = "US $54 - 60 / 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);
var rupees3 = convert (dollar3, US_to_MUR_rate);

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

答案 1 :(得分:1)

当然,这个答案的某些部分是明确编码的,除非你想要不同的



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

function convert(string, rate){
	var converted_price = string.match(/(\d+)\.(\d*)/g).map(function(number){
		return (number*rate).toFixed(2)
	})
	var unit = string.match(/(\/\s*\w+)/g)
	return "MUR Rs"+converted_price.join(' - ')+" "+unit
}

var rupees1 = convert(dollar1, US_to_MUR_rate);
var rupees2 = convert(dollar2, US_to_MUR_rate);
console.log(rupees1);
console.log(rupees2);