Using JavaScript to round up the number

I need help rounding numbers in a specific way:

Value   Expected
0,523%  1%
2,235%  2,5%
-0,081% -0,5%
-1,081% -1,5%

How can I achieve this using JavaScript?

Possible Solution:

  static round (num) {
    const abs = Math.abs(num);
    const sign = num < 0 ? -1 : 1;
    return sign * (abs % 1 > 0.5 ? Math.ceil(abs) : Math.floor(abs) + 0.5) }
}

I tried using Excel formula =round(Value/Granularity)*Granularity but couldn't get it to work in JavaScript.

 static calc(num){
    const granularitiy = 0.00005;
    let calc = Math.round((num / granularitiy)) * granularitiy;
    return calc;
  }

The granularity value I am working with is 0.00005;

Answer №1

To ensure rounding to either .5 or whole numbers, the Math.round(number) function will not suffice.

An effective alternative would be:

Math.round(number*2)/2

By using this method, your result will always be rounded to a number ending in .5 or a whole number.
If you prefer to round differently (such as ceiling or floor), simply replace Math.round with your desired function.

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

Is it possible to modify the font size of all text that shares a particular font size?

Lately, I've been pondering on a question. A few years ago, I created a website using regular CSS and now I want to make some changes to the font sizes. While I know that CSS variables are the recommended solution for this situation, I'm curious ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...

Why does the content not appear again when switching between tabs?

Hello! I'm facing an issue with toggling between two sets of content on my page. Initially, the correct content shows up, but when I switch tabs, the new content doesn't appear. Furthermore, if I click back to the first tab, that content disappea ...

Ways to include a variable in a string when using the .open("GET", "[...]") method

Is it possible to include a variable in the URL using JavaScript and PHP interaction? requeteAjax.open("GET", "../src/App/handler.php?id="); For instance, if the event number is 13, the desired URL should be: requeteAjax.open("GET", "../src/App/handler. ...

Utilizing JQuery for real-time total updates

When a new div is created by clicking a button, I want to dynamically maintain an order system where the first div is labeled as 1 of 1, then as more divs are added it should change to 1 of 2, and so on. If a div is deleted, the numbering should reset back ...

Top method for preventing an HTTP 403 error when receiving the Set-Cookie header in order to establish the CSRF Cookie

As I interact with a REST API that includes CSRF protection measures, I am facing a common hurdle. Successfully obtaining the token and sending it back to the server seems to work smoothly. However, encountering an HTTP 403 error arises when initiating t ...

Display a switch icon based on input created by the user

I've been struggling to implement a toggle button for user-generated input, specifically using a Font Awesome toggle button. Here is the link to my codepen: http://codepen.io/lucky500/pen/bdpzbd along with the code snippet: <div id="list" class= ...

Using ng-class in Angular.js with a boolean retrieved from a service: A step-by-step guide

I need to dynamically set a class based on a boolean value that is determined in a service. This example is simplified for readability, but in reality, the boolean would be set by multiple functions within the service. Here is how it would look in HTML: ...

Validate selected checkbox using JavaScript

Is there a way for me to achieve real-time updates when checking and unchecking multiple checkboxes in a list? Here's the code snippet I currently have: window.onload = function () { var input = document.getElementById('listTaxi'); fu ...

"Eliminate any inline styling from a string element with the power of JavaScript/j

If I have the following string: let sentence = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>'; This string contains multiple elements a ...

Guide to importing JavaScript in an npm package using TypeScript and JavaScript

I recently downloaded a library that includes both Typescript and its corresponding javascript version. Despite trying to declare import Library from "@scope/library", my application is only able to access the Typescript version, even after adding the .js ...

React: Content has not been refreshed

MarketEvent.tsx module is a centralized controller: import * as React from 'react'; import EventList from './EventList'; import FullReduce from './FullReduce'; import './MarketEvent.less' export default class Mark ...

Is it true that TypeScript prohibits the presence of circular references under the condition of having generic parameters

I encountered an issue of type error in the given code snippet Type alias 'bar2' circularly references itself.ts(2456) type foo = { bars: bar[]; }; //works fine type bar = foo; type foo2<T extends Record<string, unknown> = Record< ...

Issue with AddToAny plugin not functioning properly on FireFox

I’m having issues with AddToAny for social media sharing on my website. It seems like FireFox is blocking it because of tracking prevention measures. Error Message in Console: The resource at “https://static.addtoany.com/menu/page.js” was blocked d ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Use JSON data to populate a dynamic bar chart in Highcharts

As a beginner in parsing JSON objects to highcharts, I am trying to create a basic bar graph. I have managed to set up the title of the graph, but I am having trouble displaying the series that I want to show (count as series and qpAnswer as xAxis). Below ...

There is no value stored in the Angular BehaviorSubject

My attempt at creating a web-socket-client involved organizing all server messages into a BehaviorSubject. Here's the snippet of code: export class WebSocketConnectionService { public ResponseList: BehaviorSubject<WebSocketResponse> = new Be ...

The post request with Postman is functional, however the AJAX post request is not working. I have thoroughly reviewed the client-side JavaScript

I encountered a problem with an endpoint designed to create an item in my application. Sending a POST request through Postman works perfectly fine, as I am using Node.js and Express for the backend: router.post("/", jwtAuth, (req, res) => { console.lo ...

I keep encountering a double key error - MongoError: E11000 for the duplicate key error in my database. I currently have two collections set up: one for users and another

I am currently working on a project that requires the following flow: Registration -> Login -> Profile Creation -> The secret page. I have successfully implemented the registration and login routes, but I encountered an error while saving data for ...

Although req.user is undefined, the login process is functioning properly

Solution Quest This inquiry has been posed countless times, yet none of the responses have resolved my issue. In all my app's routes, the req.user call consistently returns undefined, regardless of which route I access. Interestingly, my login funct ...