Ways to steer clear of using eval for converting strings to decimal values

I currently have the fraction "1/7" and I am looking to convert it into a decimal. While I know I can achieve this using eval("1/7"), I prefer not to use eval as it is considered harmful. Are there any alternative methods to accomplish this?

Answer №1

The evaluation function is not inherently harmful. Its negative impact only arises when applied to random strings of text without verifying the input first.

Answer №2

If you want to create your own function, it's actually quite simple and efficient:

function ParseFloat(sFloat) {
    var parts = sFloat.split("/");
    if (parts.length == 2) {
        var first = parseInt(parts[0], 10);
        var second = parseInt(parts[1], 10);
        if (!isNaN(first) && !isNaN(second))
            return first / second;
    }
    return NaN;
}

To use this function:

var s = "1/7";
alert(ParseFloat(s));

You can test it live here: http://jsfiddle.net/RK3zS/

Alternatively, if you prefer working with objects, you could define a class like this:

function DecimalFraction(first, second) {
    this.first = first;
    this.second = second;
    this.toString = function() {
        return first / second;
    }
}

Then you can create instances of this class like so:

var s = new DecimalFraction(3, 7);
alert(s);

I find this approach more elegant. You can see the updated jsFiddle here.

Answer №3

Seems like we're left with no other choice. Utilizing eval isn't necessarily a bad option. Alternatively, we could develop our own function to pinpoint values and perform calculations.

Answer №4

When dealing with decimal calculations exclusively:

text = "1/7";

numerator = text.subString(0, text.indexOf('/'));
denominator = text.subString(text.indexOf('/') + 1, text.length);

result = numerator / denominator;

Answer №5

Give this a shot.

let txt = "1/7";
let result = new Function("return " + txt)()
console.log(result); // 0.14285714285714285

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 is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...

Establishing the Access-Control-Allow-Origin

I have a basic .NET web service: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; /// <summary> /// Summary description for WebService /// </summary> [WebService(Namespace = "http ...

What are the best ways to resolve the warning from webpack in Express?

I have set up webpack to bundle both the server and client side code... Below is my webpack configuration: const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin&a ...

Tips for optimizing the sequencing of 3 ajax requests, with the output of one request serving as input for the subsequent two requests

I'm currently working on a solution for chaining 3 ajax calls where the result of one call feeds into the next two. Here's the scenario: // Invoke the ajax calls firstAjax('mypage.gng','john-doe').then(secondAjax, thirdAjax) ...

Copying JSON Data in JavaScript: A Guide

Seeking advice on how to duplicate JSON within the same JSON at various hierarchy levels. Take a look at this example JSON below: Initial code snippet looks like this: { "data": { "moduleName": { "content": { "modul ...

trim() function acting strangely

There seems to be an unexpected occurrence with the trim() function, as it is removing the á character. https://i.stack.imgur.com/whZBN.png This particular code snippet is typically used in various JavaScript projects without any issues. However, a clie ...

Having trouble with missing jQuery form serialize data in CodeIgniter when using TinyMCE?

I have encountered an issue while using tinymce. I am sending data through a jQuery ajax call like this: // update textarea from tinymce tinyMCE.triggerSave (false,true); $.post ('', $('#page_form').serialize (), function (x){ var ...

The resource was treated as an image but sent with the MIME type application/octet-stream

Upon accessing my webpage, a warning message is displayed: Resource interpreted as Image but transferred with MIME type application/octet-stream The images on my page are in JPEG format. The server writes the image bytes to an output stream and sends it ...

Utilize the provided parameter within a JavaScript function

<script type="text/javascript"> function updateTrackName(trackNum) { document.form1.track_(track_number)_name.value=document.form1.track_(track_number)_parent_work.value; } </script> To modify the line inside of the parent_wor ...

Execute identical task using a for loop in JavaScript

Here is a sample code snippet: var seats = [] for (a = 0; a <= seatsNumFront; a++) { seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515")) } for (b = 0; b <= seatsNumFront; b++) { seats.push(new Se ...

What is the best way to determine the size of the URLs for images stored in an array using JavaScript?

I am working on a project where I need to surround an image with a specific sized 'div' based on the image's dimensions. The images that will be used are stored in an array and I need to extract the height and width of each image before disp ...

Issue: app.database function is not recognized with Firebase

I'm attempting to integrate Firebase realtime database into my Vue application, but I keep encountering the following error: TypeError: app.database is not a function This is what my code looks like: File: Firebase.js var firebase = require(' ...

What is the best way to include multiple views in a main HTML template in Angular?

Is there a way to load two HTML files into a base HTML file? Essentially, I have a base HTML file with a header and content view, and I want to load different HTML files into each of them. Here is the base HTML file structure: <div class="container"> ...

Manipulate JQuery plug-in properties within an AJAX request using MVC

Currently, I am utilizing a Jquery time picker sourced from Within the view, there exists this time picker control. $("#startTime").timePicker({ startTime: "09.00", endTime: new Date(0, 0, 0, 19, 0, 0), show24Hours: false, ...

Exploring nested optgroup functionality in React.js

Within my code, I am utilizing a nested optgroup: <select> <optgroup label="A"> <optgroup label="B"> <option>C</option> <option>D</option> <option>G</option> </optg ...

How can you disable a single button when clicked using the map method, and update the className after a timer runs out in React?

Is there a way to disable only one button when clicked using the map method? I currently have a disabled hook that affects all pressed buttons. Also, how can I revert the 'current__events__hot-price disabled' className back to 'current__even ...

Ways to extract information from an Object and save it into an array

In my Angular2 project, I am working on retrieving JSON data to get all the rooms and store them in an array. Below is the code for the RoomlistService that helps me fetch the correct JSON file: @Injectable() export class RoomlistService { constructor( ...

Press anywhere outside the container to conceal it along with the button

Utilizing an Angular directive to hide div elements when the user interacts outside of them has been effective. However, there is a specific issue that arises when clicking outside of a div on a button that toggles the visibility of the div. The 'ang ...

Tips for configuring ejs data within the data attribute and processing it using client-side JavaScript

My aim is to transfer leaderboard information from the server to the client-side JavaScript. This is the code on my server side: const leaderboard = [[dog,cat],[car,bus],[foo,bar]] const toJson = JSON.stringify(leaderboard) res.render('gam ...

The error message from the mongoose plugin is indicating a problem: it seems that the Schema for the model "Appointment" has not been properly registered

I need help troubleshooting a mongoose error that is being thrown. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Appointment". Use mongoose.model(name, schema) I have double-c ...