如何替换特定位置的数字

时间:2018-12-21 17:57:37

标签: javascript

我想使用一种简单的方法来使用javascript将数字替换为特定的“位置值”。例如,如果我有数字1234.567,我可能想用1代替百位数,这样我的新数字便是1134.567。

对于我的特定应用程序,我正在处理钱,因此可以确保我的电话号码只有两位小数。知道这一点,我可以实现以下类似的东西:

const reversed = String(myNumber).split("").reverse().join("");
const digitIndex = myDigit + 2; // where myDigit is the digit i want 
to replace (ones = 0, tens = 1, etc)

String.prototype.replaceAt=function(index, replacement) {
  return this.substr(0, index) + replacement+ this.substr(index + 
  replacement.length);
}

const replaced = reversed.replaceAt(digitIndex, myReplacement);
return parseFloat(replaced.split("").reverse().join(""));

这个想法是要反转字符串,因为我不知道数字会是多少,替换数字然后再次反转然后将其转换回数字。这绝对看起来像是过分杀伤力。还有更好的主意吗?

2 个答案:

答案 0 :(得分:4)

这是使用正则表达式的一种方法:

RegExp(`\\d(?=\\d{${index - 1}}(\\.|$))`)

说明

(?=\\d{${index - 1}}(\\.|$))的非捕获前瞻性匹配index - 1位数字,后跟十进制或字符串结尾

\\d要替换的单个数字(如果已匹配前向查找)

String.prototype.replaceAt = function(index, replacement) {
  const re = new RegExp(`\\d(?=\\d{${index - 1}}(\\.|$))`);
  return this.replace(re, replacement);
}

const tests = [
  {test: '123.45', index: 1},
  {test: '123.45', index: 2},
  {test: '123.45', index: 3},
  {test: '123', index: 1},
  {test: '123', index: 2},
  {test: '123', index: 3}
];

tests.forEach(({test, index}) => {
  console.log(test.replaceAt(index, 'x'))
})

更新

您可以使用它来扩展Number

Number.prototype.replaceAt = function(index, replacement) {
  const re = new RegExp(`\\d(?=\\d{${index - 1}}(\\.|$))`);
  return parseFloat(`${this}`.replace(re, replacement));
}

const tests = [
  {test: 123.45, index: 1},
  {test: 123.45, index: 2},
  {test: 123.45, index: 3},
  {test: 123, index: 1},
  {test: 123, index: 2},
  {test: 123, index: 3}
];

tests.forEach(({test, index}) => {
  console.log(test.replaceAt(index, 9))
})

更新

这是一种使用纯数学的方法

Number.prototype.replaceAt = function(index, val) {
  const a = parseInt(this / 10 ** index) * 10 ** index;
  const b = val * 10 ** (index - 1);
  const c = this % 10 ** (index - 1);
  return a + b + c;
}

const tests = [
  {test: 123.45, index: 1},
  {test: 123.45, index: 2},
  {test: 123.45, index: 3},
  {test: 123, index: 1},
  {test: 123, index: 2},
  {test: 123, index: 3}
];

tests.forEach(({test, index}) => {
  console.log(test.replaceAt(index, 9))
})

答案 1 :(得分:1)

要获得预期结果,请使用以下选项

  1. 传递三个参数-数字,位置,替换
  2. 使用位置,用替换编号更新

1223.45号返回值的详细说明

num%pos-1223.45%100 = 23.45
rep * pos-7 * 100 = 700
parseInt((num / pos)/ 10)* pos * 10 = 1 * pos * 10 = 1000

function format(num, pos, rep){
    return num % pos + (rep * pos) + parseInt((num / pos)/10)*pos*10
}

console.log(format(1223.45, 1000, 7));
console.log(format(1223.45, 100, 7));
console.log(format(1223.45, 10, 7));
console.log(format(1223.45, 0.1, 7));
console.log(format(1223.45, 0.01, 7));

codepen-https://codepen.io/nagasai/pen/xmqjdd?editors=1010