Converting a float with a comma as a decimal separator in Typescript/Javascript

I am faced with a specific problem regarding a string that needs to be parsed as a float. The string in question is:

const NumberAsString = "75,65";

Traditionally, it is recommended to replace the comma with a dot when parsing numbers where the comma acts as a thousand separator. However, in this instance, the comma serves as a decimal separator. If I were to replace it with a dot, the resulting number would be incorrectly displayed as: 7.565,00, which is not the desired outcome of 75.65. Are there any alternative methods to parse this number as a float without altering its value?

Additionally, my system has a built-in helper function that interprets numbers with dots as thousand separators and commas as decimal separators. Unfortunately, changing this functionality is not an option for me.

Answer №1

Check out this method for achieving the same result but in a more streamlined manner. Utilizing an array and reduce

const values = ['70,65', '7,000,01', '700'];

const convertNumber = (num) => {
  if(num === undefined) return undefined;
  if(num.indexOf(',') < 0) return parseFloat(num);
  const numArray = num.split(',');
  return parseFloat( numArray.reduce((accumulator, value, index) => accumulator + ((index === numArray.length - 1) ? `.${value}` : value), '') ); 
};

values.forEach(entry => console.log(convertNumber(entry)));

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 populating JsonRest store in Dojo Enhanced Datagrid

My data grid is not loading the information from the store The response I get from my REST call looks like this: {"onlineUsers":[],"offlineUsers":["123.456.7.890:8080"]} This is what my code looks like: require([ "dojo/store/JsonRest", "dojo/sto ...

The JQuery datepicker fails to function properly when the input field is modified from read-only

Utilizing the datepicker in conjunction with an MVC3 application. I aim to keep the input field as readonly until triggered by an edit button. Upon focusing on the field, I want the datepicker functionality to be activated. The code snippet below functio ...

Isolate individual musical notes from a YouTube video and showcase them using client-side technologies

Is it possible to create the following algorithm using client-side technology? The algorithm would involve: Retrieving the audio from a YouTube video while still playing on the same page. Separating the audio into individual instrument sounds. (Option: ...

Troubleshooting: Unable to Trigger jQuery AJAX Function

I've searched high and low, both here and elsewhere, in an attempt to solve this issue. Unfortunately, I haven't been able to come across anything quite like it. The button click works fine as it prints to the console. However, any subsequent con ...

Navigating to the detail page following a POST request in RTK query: A step-by-step guide

In my React RTK-query form, I am facing an issue where after a POST request is made, the form should navigate to the next step. However, in order to do that, I need to obtain the id of the newly created record. The backend auto-increments the id and does n ...

The replacement of classes in ReactJS using JavaScript seems to be malfunctioning

I have been attempting to change the class of a dynamic element when clicked, but none of my solutions seem to be working. Here is what I have tried: handleClick=(event,headerText)=>{ document.getElementsByClassName('sk-reset-filters') ...

Utilizing an Angular Component with Customized Dom Element Modifications

I've developed an Angular component that I intend to use across multiple pages in my project. This component serves as a form box with various configurations such as input fields, buttons, and check boxes. While I want the flexibility to modify the co ...

Using PHP variables in JavaScript to access getElementById

I have multiple forms displayed on a single PHP page. They all follow a similar structure: <form id="test_form_1" action="test_submit.php" method="post" name="test_form"> <label>This is Question #1:</label> <p> &l ...

The resolver function is ineffective when dealing with promise objects in Node.js

When attempting to utilize the Promise function in Node.js for file reading, unexpectedly the return promise resulted in {}. The sample code is provided below: http.createServer(function(req, res) { var readPath = __dirname + '/users.json'; ...

Tips for creating a scale animation using HTML5 Canvas

I am currently developing a canvas whiteboard tool and I have reached the stage where I am focusing on implementing the Zoom In and Zoom Out feature. While the functionality is working fine, I would like to enhance it with smooth animations for scaling. H ...

Using AppCtrl's variable in another controller

Consider the following HTML code snippet: <html ng-app ng-controller="AppCtrl"> <head> <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script> <script src="script.js"></script> </head ...

Struggling to show API images on NextJS application

I am currently exploring NextJS for the first time and attempting to showcase 3 random dog breed images on my app's webpage using the Dog.ceo API. Although I can view the three random dogs in the console through the console.log(data) line, I am facing ...

Parameter within onClick function that includes a dot

I'm attempting to design a table that enables an onClick function for the Change Password column's items so my system administrator can adjust everyone's password. Each onClick triggers the "ChangePassOpen" function which opens a modal with ...

Potential null object detected when using a ref(null)

After reading the Vue Composition API documentation, it seems I should be utilizing ref(null) within a sub-component located inside <template>...</template>. Within this sub-component, there are methods such as open(), and my current approach ...

Setting up vue-resource root and authentication configuration

Currently, I am reviewing the documentation for vue-resource that outlines how to configure it: https://github.com/vuejs/vue-resource/blob/master/docs/config.md The documentation specifies setting headers with a common authorization value: Vue.http.hea ...

The mat-slide-toggle component does not recognize the checked binding

My angular app contains the mat-slide-toggle functionality. switchValue: {{ switch }} <br /> <mat-slide-toggle [checked]="switch" (toggleChange)="toggle()">Toggle me!</mat-slide-toggle> </div> This is how the ...

When the update button is clicked, the textfield is hidden; it reappears upon refreshing the page

Our marketplace multi-vendor site on Magento allows sellers to list their products for sale. The frontend displays the price using the following code: Phtml <input onFocus="showPriceCancel('<?php echo $products->getId(); ?>');" clas ...

Substitute terms with the usage of array map

Here is an array for you (2) ['beginning=beginner', 'leaves=leave'] as well as a string its beginner in the sounds leave that has been converted to an array using the following code var words = text.split(' '); My goal ...

Is it possible to create a functionality in Google Sheets where a cell, when modified, automatically displays the date of the edit next to it? This could be achieved using a Google

Here is the current code snippet I have: function onEdit(e) { var range = e.range; var val = range.getValue(); var row = range.getRow(); var col = range.getColumn(); var shift = 1; var ss = SpreadsheetApp.getActiveSheet().getRange(row, (col+ ...

What is the proper way to disable asynchronous behavior in JavaScript?

Can someone provide assistance on how to make the following jQuery ajax function asynchronous in this code? $.post(base_url+"search/questionBox/"+finalTopic+"/"+finalCountry+'/'+findSearchText+'/'+ID,function(data){ if (data != "") { ...