Round a number to always have 1 decimal? (If it's uneven) [SOLVED]


(John Andersson) #1

Hi.

I have a textfield that sometimes outputs numbers like this:

51.20305999999000005

and sometimes like this

12

A.k.a sometimes with decimals, sometimes without.

I want to make it so that if the number has more than a decimal, the rest is invisible.

So it would like like this

51.2

Thank you.


(Per_K) #2

You can do it this way

private var longresult:Number;

private var transfer:int;

private var shortresult:Number;

Lets say that the value of longresult is 123.34256;

transfer= longresult*10; will give you 1233 since the int will drop the decimals

shortresult = transfer/10; will give you 123.3;


(azrafe7) #3

… or easier with Number.toFixed():

var pi:Number = 3.141592;
trace(pi.toFixed(2));  // 3.14
trace(pi.toFixed(0));  // 3

(Zachary Lewis) #4

This is the correct solution.