function replaceFloatDigit(number, position, newDigit) {
// Validate that newDigit is indeed a single digit
if (newDigit < '0' || newDigit > '9') {
throw new Error("Replacement must be a digit (0-9).");
}
// Convert number to string with fixed precision (10 decimal places)
let strNum = number.toFixed(10);
// Validate position
if (position < 0 || position >= strNum.length) {
throw new Error("Position is out of range for the number string.");
}
// Ensure position points to a digit
if (strNum[position] === '.' || strNum[position] === '-') {
throw new Error("Position points to a non-digit character.");
}
// Replace digit
strNum = strNum.substring(0, position) + newDigit + strNum.substring(position + 1);
// Convert back to float
return parseFloat(strNum);
}
try {
const num = 89710.291;
const pos = 2; // 0-based index
const newDigit = '8';
const result = replaceFloatDigit(num, pos, newDigit);
console.log(`Modified number: ${result.toFixed(3)}`);
} catch (e) {
console.error("Error: " + e.message);
}
/*
run:
Modified number: 89810.291
*/