JavaScript code to convert integers into decimal numbers

Currently, I am facing a challenge with my program that involves converting integers to binary and decimal. While the binary conversion is working fine, I am encountering difficulties with the decimal part. I am considering using the function intToFloat, but I am uncertain if it is the correct approach. Below is the code for the conversion functions:

if (cT[0].checked) {
    // to binary
    var dval = parseInt(val);
    if (isNaN(dval)) {
        alert("input value is not a number");
    }
    else if ((val % 1) !== 0 ) {
        alert("number is not an integer");
    }
    else if (dval < 0) {
        alert("Input value must be a positive integer");
    }
    else {
        convertByArray(dval);
    }
}
else if (cT[1].checked) {
    //to decimal
    var dval = parseFloat(val);
    if (isNaN(dval)) {
        alert("input value is not a number");
    }
    else if ((val % 1) !== 0 ) {
        alert("number is not an integer");
    }
    else if (dval < 0) {
        alert("Input value must be a positive integer");
    }
    else {
        intToFloat(dval);
    }
}
else {
    alert("Please select a conversion type.");
}
}

function convertByArray(dval) {
    var rA = new Array();
    var r,i,j;

    i=0;
    while (dval > 0) {
        r = dval % 2;
        rA[i] = r;
        var nV = (dval - r) / 2;
        $("txtCalc").value = $("txtCalc").value + " Decimal " + dval + " divided by 2 = "
       + nV + " w/Remainder of: " + r + "\n";
       i += 1;
       dval = nV;
}

for(j=rA.length-1; j>= 0; j--) {
       $("txtOut").value = $("txtOut").value + rA[j];
}

}

function intToFloat(num, decPlaces) { 
   return num + '.' + Array(decPlaces + 1).join('0'); 
}

This program should display the output of an integer being converted to a decimal, providing the value as well, similar to how it currently displays the conversion to binary.

Answer №1

convertNumber(value, fromBase, toBase)

To change the value to binary

convertNumber(25, 10, 2) //<== '25' is the value, 10 is the current base. 2 is the base you want to convert to.

To change the value to decimal

convertNumber(100011, 2, 10)

To change the value to a floating point number

var num = 203
num.toFixed(6) // answer will be 203.000000

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

What could be causing my Ajax function to malfunction?

I've been attempting to incorporate a form that sends two javascript variables to a php script and displays the result in a new Div on the same page using an ajax function. Unfortunately, it's not functioning as expected. Here is the code snippe ...

What is causing this promise chain to not return in the correct order?

Struggling with creating a promise chain that returns results in the order they are called. The current output of resultArray has some data points swapped, causing issues for downstream processing. This is my current attempt: Promise.all(data.map( (dataPo ...

Error: the function document.title is not defined and cannot be executed, occurring on line 31

I am currently working on a notification script using JavaScript, but when I try to run the js, I encounter the following error: Uncaught TypeError: document.title is not a function This is my script: function notification() { $.ajaxSetup({ cache: ...

What is the procedure for obtaining a Connect server's host name and port number?

Just like the example shown in this Express-related question, I'm wondering if there is a way to programmatically retrieve the host name and port number of a running Connect server? ...

The component 'AppComponent' cannot access the property 'results'

Having some trouble accessing the results field from a json response. The error message reads, Property 'results' does not exist on type 'AppComponent'. import { Component } from '@angular/core'; // Import `HttpClient` impor ...

Utilizing JSON API filtering within a Next.js application

Recently delving into the world of coding, I've embarked on a personal project that has presented me with a bit of a challenge regarding API filtering. My goal is to render data only if it contains a specific word, like "known_for_department==Directin ...

Sit tight as we prepare all static assets for loading on the screen

Currently, I am developing a vuejs application that will incorporate video elements. To enhance user experience, we are interested in preloading these videos upon the initial loading of the web application. I am considering using a listener like, documen ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Display a tooltip for ever-changing content

My HTML code displays dynamic rows with information, along with an image link that reveals specific details about the clicked row using the compentence_ID field. echo "<td>".$compi['Competence_ID']."</td>"; ec ...

Tips for redirecting a port for a React production environment

I am currently setting up both Express.js and React.js applications on the same Ubuntu server. The server is a VPS running Plesk Onyx, hosting multiple virtual hosts that are accessible via port 80. To ensure these apps run continuously, I have used a too ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

Activate divs with Bootstrap5 modal toggle functionality

What adjustments must be made to the Bootstrap 5 example below in order to achieve the following two objectives: The "afterAcceptingTerms" division should remain hidden until the user clicks on the Accept Terms modal button, ensuring that only the "before ...

Here is an example of how to transfer a value from PHP to a jQuery function in the code snippet provided

This is an example of my code. It is functioning properly even without passing a value. function displayMessage(text) { alert(text); } <button type="button" id="button" class="btn btn-success" onclick="displayMessage("Hello");"> Click Me </ ...

Issues with UA PhoneGap 2.0 plugin failing to initialize properly on iOS device

In my attempt to integrate push notifications into my iOS PhoneGap 2.0 app using the recently released Urban Airship plugin, I encountered an issue. Everything functions perfectly when I load the index.html from the provided sample application into my proj ...

Determining the state of a button based on a property's values

Is it possible to conditionally display a button based on the value of the sendSMS property of the logged-in user in AngularJS? How can I achieve this using ng-show in the HTML? I'm uncertain if I correctly assigned the value for the sendSMS property ...

Only authenticated users are permitted to write to Firebase databases

Currently, I am in the process of setting up a new Vue JS project for a blog with Firebase integration. The main objective is to allow any logged-in user to create blog posts that are saved in the Firebase real-time database at https://xxx.firebaseio.com/b ...

Connect directly to the DOM without using an event

A jQuery function is included in my code: $('#big-bad-bold-button') .on('click', aloha.ui.command(aloha.ui.commands.bold)); This function binds the click event. Is there a way to achieve the same binding without requiring a click? ...

Tips for implementing a search function with DynamoDB using the "contains" operator

I'm currently working on implementing a search function in my React application. Here is the structure of my DynamoDB table: --------------------- movie_id | movie_name --------------------- 1 | name a --------------------- 2 | name b ...

Substitute empty spaces and organize the text layout

I'm struggling to figure out how to substitute the whiteSpace in an aggregate request using MongoDB and also how to remove a specific part of a string (most likely requiring regex). Here's an example of my document: { "_id": "57dfa5c9xxd76b ...

Unable to find the import "@mui/x-charts/PieChart" in the file "src/components/Pie/Pie.jsx". Could the file be missing or spelled incorrectly?

I utilized the PieChart component in my pie.jsx file pie.jsx import { PieChart } from '@mui/x-charts/PieChart'; const Pie = () => { return ( <div> <PieChart series={[ { data: [ ...