I would like a simple way to replace the digit at a specific "place value" using javascript. For example if i had the number 1234.567, i might want to replace the hundreds digit with a 1 so that my new number is 1134.567.
For my specific application i am dealing with money so i am ensured that my number only has 2 decimal places. knowing this i could implement something like the following:
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(""));
The idea is to reverse the string because i dont know how big the number will be, replace the digit and then reverse again and turn it back into a number. This definitely seems like overkill. Any better ideas?