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);

1
  • Do you want 3.75 to become "3" or "4"? The answers here seem to assume you don't want it rounded. Commented Jul 27, 2018 at 18:57

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.