Skip to main content
Known Participant
June 28, 2006
Answered

Formatting Decimals

I've built a simple Batting Average calculator, but I would like to format the final decimal value so that it doesn't hava a leading zero and only has 3 digits after the decimal point. How do you format decimal values?

Here's my current code:

This topic is closed to new replies. Start a new post to keep the conversation going.
Newsgroup_UserCorrect answer
Inspiring
June 28, 2006
Ah, ok ... thought you meant "extra" zeros after decimal ... was a bit
unsure about that, my fault.

Well, you can't reformat a _number_ to be displayed that way, so you would
be forced to turn it into a string.
I don't know if you ever get any number larger or equal to 1, but that would
be something you'd need to test first, so
maybe change code to something like:
avg = Math.round(hits/ab*1000)/1000;
if (avg >= 1) {
avgText.text = avg;
} else {
var s = avg.toString();
avgText.text = s.substr(1,s.length-1);
}

this would give an output like for example
1.324
.532
.076

If you don't have numbers larger than 1 and you only want to display the
decimals, so that the example above would be
532
76
then you could just do:
avg = Math.round(hits/ab*1000)

/Jensen/

"ndisdabest" <webforumsuser@macromedia.com> wrote in message
news:e7tv3n$29q$1@forums.macromedia.com...
> That works pretty well... now is there any way to drop the zero before
> the decimal point?


6 replies

Inspiring
June 28, 2006
> u can also use Math.floor(avg) after calculating avg or
> avg = Math.floor(hits/ab)

Nah, that won't work as you have it there. Math.floor will remove all
numbers after the decimal, and in the example given leave you with 0.

--
-------------------------------
Remove '_spamkiller_' to mail
-------------------------------



Translate
Participant
June 28, 2006
u can also use Math.floor(avg) after calculating avg or
avg = Math.floor(hits/ab)
Translate
Inspiring
June 28, 2006
Hi!

Try to change to:
avg = Math.round(hits/ab*1000)/1000;

/Jensen/

"ndisdabest" <webforumsuser@macromedia.com> wrote in message
news:e7tube$177$1@forums.macromedia.com...
> I've built a simple Batting Average calculator, but I would like to format
> the
> final decimal value so that it doesn't hava a leading zero and only has 3
> digits after the decimal point. How do you format decimal values?
>
> Here's my current code:
>
>
>
> stop();
>
> var avg:Number = 0;
> var hits:Number = 0;
> var ab:Number = 0;
>
> button.onPress = function() {
> button.gotoAndPlay(2);
> hits = Number (hitsText.text);
> ab = Number (abText.text);
> avg = Number (hits/ab);
> avgText.text = avg;
> }
>


Translate
Known Participant
June 28, 2006
That works pretty well... now is there any way to drop the zero before the decimal point?

I know in ASP you could use the Right function and do something like Right(avgText,4), but I don't know if that functionality exists in ActionScript...
Translate