Exploring the utilization of arrays for computing basic operations involving negative exponents

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.

Answer №1

Have you considered exploring an alternative solution instead of continuing with the array method? Perhaps utilizing the existing Math.pow() function could provide a more straightforward way to solve this problem.

function calculateExponentialExpression(test) {
  var base;
  var multiplier;
  var exponent;

  test.replace(/^(\d+)(x)(\d+)([^])([-]?\d+)$/, function() {
    base = parseInt(arguments[1], 10);
    multiplier = parseInt(arguments[3], 10);
    exponent = parseInt(arguments[5], 10);
    return '';
  });

  console.log(base * Math.pow(multiplier, exponent));
}

calculateExponentialExpression('1x10^-4');
calculateExponentialExpression('1x10^2');
calculateExponentialExpression('4x5^3');

Answer №2

The issue arises when adjusting the decimal placement .

Instead of

arr.splice(1, 0, '.');

Consider using:

arr.splice(-exponent, 0, '.');

Check out this demo: https://jsfiddle.net/free_soul/c7nobmnj/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Problem with Integrating ControllerAs in AngularJS Routing and Application.js

Can someone please help identify the errors in the code? Issue 1: The Save button in addstudent.html is not functioning properly. It works with $Scope, but after modifying the code to use ControllerAs, the functionality ceased. Debugging revealed that con ...

Setting color values for each pixel of a createGraphics object using P5.js

The code snippet provided below is intended to set the color value of each pixel within the createGraphics object to red. However, the output only displays a gray background. ////////////////////////////////////////////////////////// function setup() { ...

Avoid having Vue CLI delete all files in the dist folder

As I work on my Vue project, I am facing a challenge in syncing the dist folder with Git. Previously, this process ran smoothly when using webpack. However, after transitioning to @vue/cli and creating my project with vue create myProject instead of vue in ...

In the realm of JavaScript, what happens when a function yields yet another function while also welcoming another function as an argument?

After following a Node & Express project tutorial on YouTube, I encountered the following code snippet in an async JavaScript file: const asyncHWrapper = (fn) => { return async (req, res, next) => { try { await fn(req, res, next); } c ...

Is there a way to extract the value of a child object from an object within the MUI Datagrid

Using the following method: useEffect(() => { PetService.getAll("/pets") .then(response => { setData(response.content); }) }, [setData]); The response obtained is as follows: { "timestamp": 167818109 ...

Automatically disconnect from the application upon logging out of Google account

I've successfully set up an express server that uses Google OAuth for user authentication. One interesting challenge I'm facing is how to handle the scenario where a user logs out of Google services (like Gmail) and automatically log them out fro ...

The process of running npm build is not resulting in the creation of the bundle.js file

I've read through many Q&A threads where people are facing the same issue, but I still can't figure out what's wrong with my code. When I run 'sudo npm run build', no bundle.js file is being created.** This is my code: index ...

Tips for linking two divs together - one containing products and the other containing options

Seeking assistance with a coding problem related to showing and hiding items within a div based on the div's ID. Specifically, I have a div containing various products and another div with options related to these products. I need help establishing a ...

Python 3 Selenium struggles to run JavaScript code

I'm currently working with Python 3 and utilizing Selenium to extract data from a website. I am attempting to eliminate a specific class from a list item in order to successfully display the desired information. Here is the code snippet in question: ...

Can you explain the significance of using curly braces in Javascript coding?

I came across the following code snippet on the page https://nodejs.org/api/modules.html: { }. Specifically, this line caught my attention: const { PI } = Math; Is there a specific term for this syntax? I'd like to learn more about it and understand ...

What is the reason behind the failure of next/script with Google reCAPTCHA?

Currently, I am in the process of upgrading from next js version 8 to version 11. I wanted to take advantage of the amazing next js feature for "next/script". However, when I tried to implement it for Google reCAPTCHA using "react-recaptcha": "^2.3.10", th ...

How can I show the real-time coordinates in a small tooltip as the mouse moves over the map in openstreetmap/leaflet?

Is it possible to have real-time coordinates displayed as a tooltip when moving the mouse over a map? For example, displaying something like: 35.56, 56.765 I attempted to implement this feature on my Wix site using the code below. The map displays correct ...

Update content dynamically with React by clicking a button

I am managing three distinct files. Nav.js var NavItem = React.createClass({ render: function() { return ( <li><a href="#">{this.props.name}</a></li> ); } }); var NavList = React.createClass({ render: function ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

Guide on using axios in vue.js to interact with the API

I need help with a functionality on my website where users can select a car brand from a list of radio buttons. After selecting a brand, I want to retrieve an array of models from the server and display them on a new page. Can someone guide me on what spec ...

I require Ajax .on to trigger during the second .on event, rather than the first one

I'm facing a challenge with implementing chained selects that trigger my ajax call on change. The issue arises when the Chained Select populates the second select prematurely causing the ajax call to fire unexpectedly. Is it feasible to bypass the in ...

Unusual marker appearing on every page utilizing ionic v1 and angularjs

For some unknown reason, a dot appears at the upper left side of each page in my webapp: https://i.stack.imgur.com/nN61t.png It seems to be an issue with the HTML code. When I run the snippet below, the dot is visible: <ion-view view-title="Send fe ...

The Node gracefully disconnects and apologizes: "I'm sorry, but I can't set headers after they have already

events.js:160 throw er; // Unhandled 'error' event ^ Error: Can't set headers after they are sent. register.js:20:18 register.js user.save(function(err) { if(err){ return mainFunctions.sendError(res, req, err, 500, ...

Troubleshooting Vue v-for loop triggering click events on multiple items simultaneously

After conducting a thorough search, I haven't found a suitable answer for my issue. The problem I am facing involves a v-for loop with buttons on each item, using VueClipboard2 to copy text. Whenever a button is clicked, some CSS changes are applied t ...

Vue 3 project experiencing issue with Bootstrap 5 tabs failing to update upon tab click

Currently, I'm in the process of developing a vue3 application with bootstrap 5. As part of this project, I am implementing tabs. Although I can successfully click on the tabs, I have encountered an issue where the tab-content remains fixed on the ini ...