Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Decimal precision in strings

1. ## Decimal precision in strings

I'm trying to write a pi calculator that shows a comparison of the calculated value to the actual value. It works, but the output of the comparison shows only the first two decimal spots, followed by two 9s.

Why is it showing two 9s and how can I make it more precise?

Code:
```<head>
<title>
Pi Calculator
</title>
<script language="JavaScript">
function calcpi(digitsn) {
p = 1;
s = 0;
for (c = 3; c < digitsn; c += 2) {
if (s == 0) {
p -= 1/c;
s = 1;
} else {
p += 1/c;
s = 0;
}
}
p *= 4;
return p;
}

function hid(input) { //Highlight Incorrect Digits
pi = "3.14159265358979323846".split('');
input = input.toString().split('');
result = "";

for (c = 0; c < input.length; c++) {
if (input[c] != pi[c]) {
//result += "; " + input[c] + "!=" + pi[c];
result += "<span style='background-color:red'>" + input[c] + "</span>";
} else {
result += input[c];
}
}

return result;
}
</script>
<body>
Repeat algorithm x many times:<br/>
<input type="text" value="10000" id="digitsx"/><br/>
Result:<br/>
Correct value:<br/>
<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid('3.1499')"/>
<div id="comparison"/>
</body>```

• What? But you are directly telling it to compare 3.1499 and not the actual result. Therefore it cannot be any more precise.

Change this line
Code:
`<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid('3.1499')"/>`
to that
Code:
`<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid(document.getElementById('answer').value)"/>`

• Originally Posted by devnull69
What? But you are directly telling it to compare 3.1499 and not the actual result. Therefore it cannot be any more precise.

Change this line
Code:
`<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid('3.1499')"/>`
to that
Code:
`<input type="button" value="Compare" onClick="document.getElementById('comparison').innerHTML = hid(document.getElementById('answer').value)"/>`
Oh gosh... how embarrassing! I forgot I put that there when I was just screwing around. Thanks for pointing out my stupidity

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•