Decrease float accuracy in Javascript?

Asked

Viewed 471 times

2

How to decrease the decimals of a float number in javascript?

For example, I want 3.3333333333 become in 3.34.

What is the simplest way to do this in javascript?

I tried functions like Math.ceil, but it returns me the whole value.

float_value = 3.333333;
Math.ceil(float_value); // 4
  • 1

    You can also use the .toPrecision() http://jsfiddle.net/cks2mvr9/

  • 1

    @qmechanik, you should post as an answer, to win +1, rsrsrsrsrsrsrs

2 answers

2


Use the function Math.round() which returns the value of the nearest integer.

Math.round(num * 100) / 100

You can also use the function toFixed():

parseFloat("123.456").toFixed(2); // Se for uma string, converta pra numéro
  • 1

    Slim, buddy. But I’d like to know if Javascript has some way of doing natively?

  • 1

    I believe that a native function for this does not have, I think only in hand, :)

  • 1

    You can also use toFixed...

  • 1

    I haven’t gotten used to it yet: In pure javascript, a lot is at hand ;)

1

You can use the toFixed() to do this, but it returns a String, and not a float. From the site itself:

var num = 5.56789;
var n = num.toFixed(2);

results in

5.57

There is an argument about this in ONLY THE GRINGO.

  • Thank you, Caio. I had been thinking about .toFixed, but it returns a string. But, in that case, I would only have to use parseFloat(num.toFixed(2))

  • It’s a turn, but it works!

  • 2

    We therefore have: http://jsfiddle.net/mqzbsgxf/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.