convert a negative number to positive without affecting decimal points in js

Viewed 900

I need to convert a negative number to a positive number. My attempt is as below.

Math.abs(-4.0);

It will return 4 as the answer. But I need 4.0 as the answer. Here I don't know the decimal places to be set. For different numbers, there's a different decimal point value. Actually, that will totally depend on the web socket output. According to the input value, the server-side defined different floating points which there's not any pattern according to our requirement.

So in js, is there any better way to handle this without getting decimal places separately?

3 Answers

As mentioned in other comments, you won't be able to keep the precision. toFixed() is definitely not a solution and this problem has valid case scenarios.

We had to do something similar where teachers would input a grade (90.05) and were expected to keep the same number of decimals for all their students inside of a single gradebook. Teachers grade differently depending of the situation:

Teacher A | Teacher B | Teacher C
   90          90.5       4.95
   80          88.5       3.80
   75          80.0       5.00

One way to solve this, especially if the request comes as a string (from an input, http request, etc.), is to maintain the number as a string and return a string value.

Note that this is a very crude implementation (our implementation is more fail-safe), but the idea is simple:

function absString(n) {
  numberString = n.toString();
  if (numberString[0] === '-') {
    return numberString.substring(1);
  }
  else {
    return numberString;
  }
}

console.log(absString('-1'));
console.log(absString('-2.0'));
console.log(absString('2.0'));
console.log(absString('-0.57'));

You can use the number toFixed method as follows:

var decimalPlaces = 5 // Change this to change the number of decimals

console.log(Math.abs(-4.0).toFixed(decimalPlaces))

If this is for display purposes only you can use the Intl.NumberFormat object to format your value appropriately. Example:

Intl.NumberFormat(
  undefined,
  { signDisplay: 'never', minimumSignificantDigits: 3, maximumSignificantDigits: 20 }
).format(-4.06364635454000); // "4.06364635454"
Intl.NumberFormat(
  undefined,
  { signDisplay: 'never', minimumSignificantDigits: 1, maximumSignificantDigits: 20 }
).format(-4.0); // "4"
Intl.NumberFormat(
  undefined,
  { signDisplay: 'never', style: 'currency', currency: 'EUR' }
).format(-4.06364635454000); // "€4.06"
Related