Falling Rock
Falling Rock

Reputation: 23

Length of string results in google apps

I've a function in gApps spreadsheet that takes a dollar figure multiplies by 100 and then returns the length of the string...

function checkWrite(amount) {
amount = amount * 100
amount = amount+'';
var aLength = amount.length;
return(aLength);

Return gives the following results: amount--length
4. ---- 3
4.01 -- 3
4.02 -- 18
4.03 -- 3
4.04 -- 3
4.05 -- 3
4.06 -- 18

... and so on. I get many correct answers, 3, and some random wrong ones 18.

Can anyone shed some light on what's going on? I'm not great at coding, but I'm pretty sure that results should be consistent anyway.

Upvotes: 2

Views: 6327

Answers (1)

Henrique G. Abreu
Henrique G. Abreu

Reputation: 17752

Most likely the numbers are not rounded as you'd expect. Float point values are not exactly represented as you're thinking. To check that you should return the string representation generated as well, e.g. change the last line to return aLength+' '+amount;

Anyway, what's the usage of such function? If I have any idea on what you use it for, I could suggest some alternative solution.

Upvotes: 1

Related Questions