/    Sign up×
Community /Pin to ProfileBookmark

two decimal Places

In this code how does the total will be come two decimal places

[code=html]
<script type=”text/javascript” language=”javascript”>

function autocalc(oText)
{
if (isNaN(oText.value)) //filter input
{
alert(‘Numbers only!’);
oText.value = ”;
}
var field, val, oForm = oText.form, total = a = 0;
for (a; a < arguments.length; ++a) //loop through text elements
{
field = arguments[a];
val = parseFloat(field.value); //get value
if (!isNaN(val)) //number?
{
total += val; //accumulate
}
}
oForm.total.value = total; //out
}

</script>

[/code]

Thank you

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@pactor21Oct 14.2011 — var num = 5.123456;

num.toPrecision(1) //returns 5 as string

num.toPrecision(2) //returns 5.1 as string

num.toPrecision(4) //returns 5.123 as string

I'm guessing num.toPrecision(3) will work?
Copy linkTweet thisAlerts:
@007JulienOct 14.2011 — See Number object w3schol.com :

toPrecision(x) : Formats a number to x length.

toFixed(x) : Formats a number with x numbers of digits after the decimal point.

An other (valid on all old browsers) way is
[CODE]var num=3.1415925,twoDec=100;
num=Math.round(twoDec*num)/twoDec;
[/CODE]
Copy linkTweet thisAlerts:
@KorOct 14.2011 — <i>
</i>oForm.total.value = total.toFixed(2);

Note that the toFixed() returns a [I]String[/I].
Copy linkTweet thisAlerts:
@rhodaroseauthorOct 17.2011 — Thank you...

I will try the tofixed(2) syntax...I search for the round to two decimal places and i fopund the math.round but I dont know how can I used it in my code..

Thank you
Copy linkTweet thisAlerts:
@rhodaroseauthorOct 17.2011 — Thank you for your suggested code.I used toFixed(2) and it is work..Thank you so much..
×

Success!

Help @rhodarose spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.15,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...