/    Sign up×
Community /Pin to ProfileBookmark

Coding problems

the following code seems to work with any number other than 12.3 however I need it to accept 12.3 with 12.3 it gives :

54.099999999999994

// runner times
var carlos = [9.6,10.6,11.2,10.3,11.5];
var liu = [10.6,11.2,9.4,12.3,10.1];
var timothy = [12.2,11.8,12.5,10.9,11.1];

// declare your function calculateTotal here
var calculateTotal= function(raceTimes){
var totalTime;
var raceTime = raceTimes[0];
var i =0;
for (i = 0; i< 4; i++){

raceTime = raceTime+raceTimes[i];
totalTime = raceTime;
}
return totalTime;

};
var liuTotal = calculateTotal(liu);

console.log(liuTotal);

to post a comment
Full-stack Developer

1 Comments(s)

Copy linkTweet thisAlerts:
@SpinnerMar 30.2012 — [CODE] // runner times
var carlos = [9.6,10.6,11.2,10.3,11.5];
var liu = [10.6,11.2,9.4,12.3,10.1];
var timothy = [12.2,11.8,12.5,10.9,11.1];

// declare your function calculateTotal here
function calculateTotal(raceTimes){
var totalTime=0.00;
var raceTime=0.00;
var i = 0;
for (i = 0; i < raceTimes.length; i++){ // replaced the 0-4 loop with this one, being a bit more friendly with handling more than 4 time-entries
if (typeof raceTimes[i] == 'number'){ // Just a little extra check!
raceTime += raceTimes[i]; // adding to raceTime
}
else {
console.warn(raceTimes[i]+ 'is not a number'); // Just a friendly warning
}
}
totalTime=raceTime.toFixed(2); // Forcing 2 decimals on the output format
return totalTime;
};
var liuTotal = calculateTotal(liu);

console.log(liuTotal);
[/CODE]


That should take care of your problems, I believe.

The problem lies in how computers work with floating-point numbers. If you want details, I recommend this link : http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
×

Success!

Help @Spartan117 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,
)...