admin管理员组

文章数量:1297132

I want to ensure that a number is positive, and if not return its mirror

I have started with this

var pos = Math.sqrt(x*x);

Is there a better, more efficient way?

I want to ensure that a number is positive, and if not return its mirror

I have started with this

var pos = Math.sqrt(x*x);

Is there a better, more efficient way?

Share asked Feb 13, 2012 at 10:21 Mild FuzzMild Fuzz 30.8k34 gold badges105 silver badges151 bronze badges 1
  • 3 I think Math.sqrt(x*x) is the most inefficient way :) – Sergey Gavruk Commented Feb 13, 2012 at 10:27
Add a ment  | 

3 Answers 3

Reset to default 8

Use Math.abs.

Example: document.write(Math.abs(-5)).

You should use Math.abs(number) to do that.

The abs() method returns the absolute value of a number.
var pos = Math.abs(x)

本文标签: javascriptIs there a better way to ensure a number is positiveStack Overflow