2

Guys I'm working on a native script project

I'm hitting an API and in response, I'm getting the rating of restaurants. Like[3.75, 3.57, 4.6]

What I want to do is, remove values after decimals whether it's precision scale is 1 or 2 or any

Currently I'm trying it with

parseFloat(3.75).toFixed(2)

But I'm getting 3.75 as it is.

Any idea how can I fix it?

var v = parseFloat(3.75).toFixed(2);
console.log(v);
Saleh Mahmood
  • 1,823
  • 1
  • 22
  • 30
  • Do you want 3.75 to become "3" or "4"? The answers here seem to assume you don't want it rounded. – SamVK Jul 27 '18 at 18:57

3 Answers3

4

If you don't want any numbers after the decimal, with Javascript you can use Math.trunc(3.75)

"The Math.trunc() function returns the integer part of a number by removing any fractional digits."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc

Edit: if you do want the ability to be flexible with how many places after the decimal you have, you can do something like they discuss here which allows you select the number of digits after the decimal: Truncate (not round off) decimal numbers in javascript

Alexandra
  • 423
  • 5
  • 10
2

toFixed(2) => Only use for maintaining number of decimal after dot.

By using parseInt

var result = [3.75, 3.57, 4.6];

result = result.map(val=>parseInt(val));

console.log(result);

By using split and string but It will convert in string every value of array.

var result = [3.75, 3.57, 4.6];

result = result.map(val=>(val+"").split(".")[0]);

console.log(result);
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
1

Simply use parseInt():

var v = parseInt(3.75);
console.log(v);

Or Another approach can be to use Math.trunc()

 var v = Math.trunc(3.75);
 console.log(v);

In case you want the number to be rounded of to the smallest integer greater than or equal to a given number. You can use Math.ceil()

var v = Math.ceil(3.75);
console.log(v);

If you want the number to be rounded of to the largest integer less than or equal to a given number.You can use Math.floor()

var v = Math.floor(3.75);
console.log(v);
amrender singh
  • 7,949
  • 3
  • 22
  • 28