Check if the value is a string and contains a floating point number; if so, parse and format the float

I need to work on formatting decimal values returned by an API that only responds with strings. The requirement is to add a leading zero but no trailing zeros to any decimal value in the string. If the value is not a float, it should remain unchanged.

For example, if the input is ".7", ".70", or "0.70", my function should always return "0.7". Similarly, for inputs like "1+", it should just return "1+".

Initially, I had assumed that the API was sending floats, so I used the following approach considering the number of decimal places required as a parameter:

function setDecimalPlace(input, places) {
    if (isNaN(input)) return input;
    var factor = "1" + Array(+(places > 0 && places + 1)).join("0");

    return Math.round(input * factor) / factor;
};

How can I modify the above function to achieve the same result when the input is a decimal string, while returning the original value if it's not a float? Additionally, I am working with Angular and plan to convert this into a filter.

Answer №1

UPDATE #2

Additionally sourced from

function checkInteger(n) {
   return n % 1 === 0;
}

At the end, you can verify if it's a Float, then an Int, and eventually conclude that it's a String.

Referencing your comment on '7.0':

var value = '7.0';
var formattedValue = (isFloat(value) || isInt(parseFloat(value))) ? parseFloat(value) : value;

UPDATE

Actually, there's no necessity for the numberFormat function:

var value = '.7';
if(isFloat(value)) var formattedValue = parseFloat(value);

Utilize these functions:

function isFloat(num) {
  num = parseFloat(num);
  // obtained from https://stackoverflow.com/a/3886106/4640499
  return num === Number(num) && num % 1 !== 0;
}
function numberFormat(e, t, n, o) {
  // sourced from http://phpjs.org/functions/number_format/
  var r = e,
    u = isNaN(t = Math.abs(t)) ? 2 : t,
    c = void 0 == n ? '.' : n,
    a = void 0 == o ? ',' : o,
    l = 0 > r ? '-' : '',
    d = parseInt(r = Math.abs(+r || 0).toFixed(u)) + '',
    s = (s = d.length) > 3 ? s % 3 : 0
  ;
  return l + (s ? d.substr(0, s) + a : '') +
    d.substr(s).replace(/(\d{3})(?=\d)/g, '$1' + a) +
    (u ? c + Math.abs(r - d).toFixed(u).slice(2) : '');
}
function formatFloat(e) {
  return numberFormat(e, 1);
}

Then:

var value = '.7';
console.info(isFloat(value));
console.info(formatFloat(value));

if(isFloat(value)) formatFloat(value);

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

Issue with fullPage.js - Unable to scroll to footer on the last section of the page

I'm currently working with the fullPage.js plugin () and encountering some issues. While sliding through each section, everything functions as expected. However, when I reach the last section and try to scroll down to the footer below it, I encounter ...

Utilize images stored locally in ReactJS

My path to the image is: ../src/assets/images/img_name.jpg" And my path to the file.js is: src/file_name.js If I include the following code in file.js: Import img_name from "../src/assets/images/img_name.jpg" Then reference the image pa ...

Protractor - I am looking to optimize my IF ELSE statement for better dryness, if it is feasible

How can I optimize this code to follow the D.R.Y principle? If the id invite-user tag is visible in the user's profile, the user can request to play a game by clicking on it. Otherwise, a new random user will be selected until the id invite-user is di ...

Enhance your images with the Tiptap extension for customizable captions

click here for image description I am looking to include an image along with an editable caption using the tiptap extension Check out this link for more information I found a great example with ProseMirror, but I'm wondering if it's possible ...

I am interested in sending an email from a PDF document based on the selected check boxes

I have added a button in a PDF form that says "send an email" and I would like the form to be sent to different email addresses based on which checkboxes were selected previously. For example, there is a question about the "Size of the company" with 2 che ...

JavaScript - Sending Form Data with Local Time

I want to automatically submit a form at a specific time of day The form should be submitted every day at "15:30:00" Here is the JavaScript code I have written: <script type="text/javascript> function initClock() { var now = new Date(); var h ...

Securely transmit ID values through ajax calls

Picture this: I have a website where users' profile pages are accessed through addresses like the following: http://www.samplewebsite.com/profile.php?p=123 Now, I want to be able to block or perform another action on a user when I click a button. To ...

"Troubleshooting the issue of Delete Requests failing to persist in Node.js

Whenever I send a delete request to my node.js server, it can only delete one item from my JSON file until the server restarts. If I attempt to make a second delete request, it successfully deletes the item but also reverts the deletion of the last item. ...

Creating uniform line lengths with a ruler utilizing Fabric.js

I have a div that scrolls horizontally and contains a ruler div and a canvas where I draw horizontal lines of varying lengths. When drawing the lines, I want to ensure they are accurately measured against the ruler using JavaScript and CSS: var canvas = ...

Looking to retrieve data using Cheerio? If you're finding that the data appears empty in the page source but is visible when inspecting the elements, here's how you can go

I am encountering difficulties while trying to scrape data from another website. In my case, I notice that the data appears empty when viewing the page source, but it is visible when inspecting the elements. If you're confused, please refer to the fol ...

What is the method for setting a function as the initial value of a state variable?

Here is a function I have: async function setAllValues(value) { await stableSort(rows, getComparator(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .forEach((row) => { temp = ...

Creating an array object in JavaScript is a straightforward process that involves using the array

Looking to achieve the following object list structure: myObj = {"foo":[1,2,3,4], "bar":[3,5,7,8]} Initial attempt was unsuccessful: var myObj = new Object(); myObj["foo"].push(1) myObj["foo"].push(2) #...etc Seeking guidance on the correct m ...

Tips for utilizing jQuery to display images similar to videos

Are there any plugins available that can create a video-like effect on images by incorporating scroll, pan, tilt, zoom (in/out) transitions for a few seconds before fading to the next image? I've searched but haven't found anything quite like thi ...

The form validation feature is not functioning as expected when integrating mui-places-autocomplete with MUI React

I'm currently working on implementing an autocomplete feature using Google Places API in my project with Material UI React, Redux-Form, Revalidate, and MUI-Places-Autocomplete. Although I've successfully integrated the place lookup functionality, ...

Displaying a group of elements in ReactJS

I'm currently working on assembling an array using different JSX components. There's a function I've created that populates this array with components and then returns it. let components = []; switch (obj.type) { case 'title': ...

unable to retrieve the city name through geographical location information

I am currently using the following code snippet to retrieve the country and city names: <?php $user_ip= getenv('REMOTE_ADDR'); $geo= unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip")); $city= $geo["ge ...

What is the best way to reach the parent controller's scope within a directive's controller?

In a scenario where I have a custom directive nested inside a parent div with a controller that sets a variable value to its scope, like this: html <div ng-controller="mainCtrl"> <p>{{data}}</p> <myDirective oncolour="green" ...

Shadows are not being cast by ThreeJS

I'm in the process of creating a simple Three JS application. As I familiarize myself with Three JS, I've been experimenting with different features. Currently, I am working on constructing a scene that includes a floor, an object, and a light so ...

Generate barcodes using Angular 2

Can anyone point me in the direction of an Angular 2 Barcode Generator capable of creating code 128 barcodes? I've been searching but haven't had any luck finding one. If you have any suggestions or can offer assistance, it would be greatly appr ...

The set interval function in JavaScript does not properly call PHP in Internet Explorer

I'm currently implementing code to display the updated message from the database. Here is what I have so far: var showtime = setInterval('redirect()',5000); ////Redirecting to DB Status ///// function redirect() { xmlhttp = GetXmlHttpOb ...