/    Sign up×
Community /Pin to ProfileBookmark

Javascript: parseFloat(): Rounding

Hi!
How would I restrict Javascript to only 2 digits after decimal point.
e.g.
alert( “2544.56 + 1991 + 480 = ” + 2544.56 + 1991 + 480 ) ;

The above line gives me result : 2544.561991480

How would I get only : 2544.56

I tried parseFloat(), eval().

Thanks,

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@NevermoreFeb 10.2003 — For a start, you are using strings, so javascript is just putting them together, not adding them. You need to create them using the float command, or if you are getting them from somewhere, process them with parsefloat(). Then, to round to two decimal places, use the following code: (assumes the total of all your numbers is a floating point number called
[CODE]num[/CODE].

[CODE]
Math.round(num * 100) / 100;
[/CODE]
Copy linkTweet thisAlerts:
@Dan_DrillichFeb 11.2003 — Please look at -

http://forums.webdeveloper.com/showthread.php?s=&threadid=3591&highlight=toFixed

Please try -

<i>
</i>alert( "2544.56 + 1991 + 480 = " + (2544.56 + 1991 + 480).toFixed(2) ) ;


Cheers,

Dan
×

Success!

Help @sk24 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 5.4,
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: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

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