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

What are some effective strategies for optimizing the organization of express middlewares?

Currently, I have successfully implemented the following code using node and express. The code is located in file app.js app.use(function (req, res, next) { fs.mkdir('uploads/', function (e) { if (!!e && e.code !== 'EEX ...

Is it feasible to establish a direct link between an Angular.js application and Dynamodb? Are there any other solutions available to eliminate the need for a backend

Personally, I believe that removing the backend could be a successful strategy for addressing sysadmin/scale issues. Do you agree with this approach? Is there a proven method for eliminating the backend in web applications that require database access? I& ...

Using the symbol for pi in a JavaScript program rather than its numerical value, while still performing calculations with the numerical value behind the scenes

I am working on a calculator project where I want the symbol for pi to be displayed instead of the numerical value. Here is the relevant function: function Pi(pi) { document.getElementById('resultArea').innerHTML += pi; eval(document.ge ...

I'm working on separating the functionality to edit and delete entries on my CRM model, but I'm having trouble finding a way to connect these buttons with my data fields

I am encountering some difficulties while trying to implement separate functionality for editing and deleting items on my CRM model. I have already created the necessary API in Angular, but I am struggling to bind these buttons with my field. Any assistanc ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

What is the best way to emphasize case-insensitive searchtext matches in JavaScript?

If I have data containing words like Krishna, krishna, KRISHNA and I enter the search text as 'krish', it will retrieve all three words. However, when I want to highlight the matching result, only the exact matching part of the string is highligh ...

Ways to implement material-ui button design on an HTML-native button

I am using pure-react-carousel which provides me an unstyled HTML button (ButtonBack). I would like to customize its style using material-ui. Trying to nest buttons within buttons is considered not allowed. An approach that works is manually assigning th ...

Convert a prop into a data attribute using Vue.js 2

I have a basic component being displayed as <House :_people="[{'name': 'Kevin'}, {'name':'Bert'}, {'name': 'Timmy'}]"></House> The structure of the component is like this: <templ ...

"Ensuring Username Uniqueness in AngularJS and CakePHP3: A Step-by-Step

<input type="email" id="username" dbrans-validate-async="{unique: isUsernameUnique}" ng-model="username" required class="form-control" name="username"> $scope.isUsernameUnique = function(username) { $http.get(url+'/isUsernameUnique&apo ...

What is the best way to display JSON data in a Listview control?

What is the best way to display JSON data in a list format? Currently, I am able to retrieve JSON data and display it in an alert dialog. The JSON data looks like this: [{"_id":"5449f20d88da65bb79a006e1","name":"name3","phone":"888888","service":"service ...

What is the best way to find out if multiples of a specific time interval can evenly divide the time between two

I'm currently utilizing Luxon for handling dates and durations. I have two specific dates and an ISO duration, and I am looking to figure out how to determine if the interval between the dates is a multiple of the specified duration without any remain ...

What is the best way to link a multi-select element with an array of objects?

How can I bind a select element with a model to get/set the value and populate it from a list using angular 1? Currently, I'm able to bind it from UI to model, but not vice versa. What am I doing wrong? HTML: <div ng-controller="MyCtrl"> ...

"Learn how to dynamically update the user interface in express.js using handlebars without having to refresh the

As a newcomer to using express.js and Handlebars, I am faced with the challenge of implementing autocomplete functionality. Specifically, I want to enable autocompletion in a text input field without triggering a page refresh when users interact with it. C ...

What is the best way to save items for later use with the .not() method?

Is there a way to combine $( "#c1" ).parents() with the .not() function successfully? I considered saving the selector in a variable, for example: var ele = $( "#c1" ).parents(); However, I wasn't sure about the next steps or how to proceed. ...

How to transfer data from JavaScript to PHP using AJAX

After spending countless hours attempting to make this function properly, I have come to you for assistance :) I have created a PHP page that can exhibit files from a server. I am able to modify the files using an editor plugin, where the Textarea tag is ...

Colorbox scalePhotos function malfunctioning

The scalePhotos option in Colorbox does not seem to be working correctly for me. I have tried various methods to set it, including initializing Colorbox using the following code snippet right before the closing </body> tag in my HTML: jQuery('a ...

Using Javascript to deactivate a clickable image upon clicking another image

I have two buttons with alert functions assigned to each. I want the function on the first button to only work when that button is clicked, and not work if the second button has been clicked. Below is the code I've tried, but it's not functioning ...

Creating specific CSS classes for individual slides in a basic slider framework

So, I have a rather simple slider that is created using only CSS. Each slide has unique labels for navigation buttons. The main question here is: how can I dynamically add or remove classes to specific items on the slide only when that particular slide is ...

Display a preview image at the conclusion of a YouTube video

I am currently working on an iOS device and have a Youtube video thumbnail that, when clicked, disappears and the video automatically plays in fullscreen mode using an iframe. It's working perfectly. Now, I would like to know how I can make the thumb ...

Error encountered: The function 'showErrorMessage' is not exported from the file '../helpers/alerts'

Within the directory ../helpers/alerts, there is a file called alerts.js const displaySuccessMessage = (success) => { <div className="alert alert-success">{success}</div> } const displayErrorMessage = (error) => { <di ...