Utilizing jQuery to seamlessly animate decimal values

Currently facing a challenge while trying to animate a number from 0 to 36.6. The issue is that the end value gets rounded up to 37 instead of displaying as 36.6, which you can observe in this fiddle: http://jsfiddle.net/neal_fletcher/0f3hxej8/
Required markup provided below:

HTML

<div id="el"></div>

jQuery:

// Animate the element's value from x to y:
  $({someValue: 0}).animate({someValue: 36.6}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $('#el').text(commaSeparateNumber(Math.round(this.someValue)));
      },
      complete:function(){
          $('#el').text(commaSeparateNumber(Math.round(this.someValue)));
      }
  });

 function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.");
    }
    return val;
  }

Looking for suggestions on how to make it animate through decimals as well, like 35.9, 36.0, 36.1, 36.2 and so on. Any help or input would be highly valued!

Answer №1

If you want to round to a single decimal point, one method is to first multiply by ten, then round the number, and finally divide by ten again.

Math.round(this.someValue * 10) / 10)

This technique can be seen in action in your recently updated jsfiddle.

Answer №2

If you're looking for a quick fix, consider utilizing the Math.round10 function from MDN. All it takes is modifying your code to this:

 $('#el').text(commaSeparateNumber(Math.round10(this.someValue, -1)));

Check out the Updated Fiddle!

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

``It seems like there was an error with WebComponents and NextJS - the hydration failed due to a mismatch between the initial UI and what was rendered on

I'm running into an issue with the following error message: Error: The initial UI doesn't match what was rendered on the server, leading to hydration failure. This problem occurs when I have a NextJS webpage that includes StencilJS web compone ...

In order to maintain a custom tooltip in an open state until it is hovered over, while also controlling its

When hovering over the first column of the table, a tooltip will appear. Within each material tooltip, I would like to include a button at the bottom right after the JSON data. When this button is clicked, it should open an Angular Material dialog. <ng ...

How can I deselect the 'select-all' checkbox when any of the child checkboxes are unchecked?

Here is the code provided where clicking on the select-all checkbox will check or uncheck all child checkboxes. If any child checkbox is deselected, the 'select-all' checkbox should also be unchecked. How can this be achieved? $(document).read ...

Designing motion graphics for a browser game

As I delve into learning about Node.js, Angular.js, Socket.io, and Express.js, my current project involves creating a multiplayer poker game like Texas Hold 'Em. However, despite spending a considerable amount of time browsing the internet, I have bee ...

Utilizing a lone div for clearing a float

For a long time, my go-to method for clearing floats has been using <div style="clear:both;"></div>. However, I recently began wondering if in HTML as XML, could I simply use <div style="clear:both;" /> since they essentially serve the sa ...

Utilizing JQuery and AJAX to update and save WordPress session variables

I am new to working with WordPress and encountering some challenges that I need assistance with. My objective is to update a session variable with the input provided by the user in a textbox. Once updated, I aim to save this session variable to a text fi ...

The functionality of the button seems to be malfunctioning specifically in the Mac Firefox

My button isn't working in Mac Firefox only. Below is the code: <button class="col btn-change"><a href="/p/88" style="color: white;">Landscape</a></button> However, the following two codes are functioning correctly. In the fi ...

Updating Array Values in AngularJS based on Input Text Box Modifications

In my application, there is a text box that looks like this - <input type="text" class="form-control" id="inputID" name="ItemId" ng-model="inputItemId" ng-required="true" ng-blur="addValueToArray(inputItemId)"/> The user has the ability to add or r ...

The array.slice() method fails to work properly when I try to start it from any index other than 0

I am currently working with an array called $scope.results which contains 8 objects. I have also created a custom simple pagination and a function called selectAll() that I'm trying to get to work together. Please refrain from suggesting the use of b ...

Using dataloader on ammap effectively involves importing the necessary data into the platform

I've been attempting to implement the dataloader feature on ammap without success. Here is my current approach: var birth_map = AmCharts.makeChart( "il_bazinda_dogum_say_dagilim", { "type": "map", "data": { ...

Switch between pages within a reactjs application by utilizing react router

Greetings! I am currently diving into the world of reactjs and experimenting with navigation from one page to another by simply clicking on a link through react router. In my home.js file, I have listed out some interesting places and I aim to click on one ...

Use Enums instead of conditions in Typescript

Consider the code snippet below, which is a function that generates a CSS class based on the value of toCheck: const computeSomething = (toCheck: string) => { return clsx('flex', { 'flex-start': toCheck === 'FIRST', ...

"Mastering the art of running a successful Dojo

As I delve into learning dojo, I encountered some peculiar syntax in a project on GitHub. dojo.declare('app.services.Favorites', [ dojo.store.Memory ], { constructor : function() { this.inherited(arguments); dojo.subscribe(& ...

How come outerHTML retrieves <!-- --> comments?

I came across a jsfiddle link that showcases the collection of outerHTML for elements with a class='active'. Surprisingly, even when certain parts of the HTML are commented out like this: <!-- <div>'Some inner text'</d ...

Several validation checks - logic malfunction

I have implemented a validation feature for passwords on a form, but I suspect there may be a logic error in my code that I haven't caught yet (blame it on the coffee machine!). Take a look at the JavaScript below: <script type="text/javascript"& ...

Is there a way to set a max-width using a Pseudo class

I am utilizing a css tooltip that is linked to a span element in the following manner: <span class="mytooltip" data-mytooltip="Text here. Text here. Text here. Text here. Text here. Text here. Text here. Text here. Text here."> Has Tooltip </ ...

Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID. However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers. <template& ...

Is it possible to change the order of elements in the navbar using HTML/Bootstrap depending on the state of the responsive menu toggle?

I am attempting to implement a responsive Bootstrap 4 navbar within Angular 8. When the menu is closed, the element order is correct: COMPANY, BROWSE, LOGIN The issue arises when I open the menu and the #menu receives the navbar-collapse flex attributes: ...

Guide on organizing items into rows with 3 columns through iteration

Click on the provided JSFiddle link to view a dropdown menu that filters items into categories. Each item is stored as an object in an array for its respective category. Currently, all items are displayed in one column and I want to divide them into three ...

Use Protractor to simulate Loss Connection by clearing LocalStorage in a Spec

Currently, I am utilizing the code window.localStorage.removeItem("name of localStorage variable you want to remove"); to eliminate two distinct localStorage Keys within a particular specification, and it is successfully removing them. Afterwards, I proce ...