In my attempt to create a function that correctly calculates the result of multiplying a number by a negative power of ten using arrays and the split()
method, I have encountered some challenges. For instance, when the length of the number exceeds the exponent value, the output is not as expected. My code treats the variable num
as a string, splitting it into an array for further manipulation as demonstrated below:
// Code snippet where num is treated as a string and split in an array inside get_results() function
// Note that 'exponent' is a numerical value
// Experiment with different values for 'exponent' and 'num' lengths to replicate the issue
// For example, setting 'num' to 1234 and 'exponent' to 2 will yield 1.234 instead of 12.34
var num = '1';
var sign = '-';
var exponent = 2;
var op = 'x10^'+sign+exponent;
var re = get_result(num);
console.log(num + op +' = '+ re);
function get_result(thisNum) {
if (sign == '-') {
var arr = [];
var splitNum = thisNum.split('');
for (var i = 0; i <= exponent-splitNum.length; i++) {
arr.push('0');
}
for (var j = 0; j < splitNum.length; j++) {
arr.push(splitNum[j]);
}
if (exponent > 0) {
arr.splice(1, 0, '.');
}
arr.join('');
}
return arr.join('');
}
View the demonstration here: https://jsfiddle.net/Hal_9100/c7nobmnj/
I have attempted various solutions to address discrepancies in results between different lengths of num
and various values of exponent
, but none have proven successful. I am now at a standstill and seeking insights on how to overcome this challenge.
You can review my latest attempt here: https://jsfiddle.net/Hal_9100/vq1hrru5/
If you have any ideas on how to resolve this issue, please share them. Your input is greatly appreciated.
PS: While I am aware of rounding errors resulting from JavaScript's floating-point conversions, which can be mitigated using toFixed(n)
or third-party libraries, my primary objective is to enhance my proficiency in crafting pure JavaScript functions.