I am not very familiar with JavaScript and/or form calculations. The form and script I made after searching the internet about the topic.
How can I round the output (output_abc) in 0.5 steps (1.0 1.5 2.0 … 7.7=7.5 or 7.8=8.0) and where to place it? How can I (after rounding the output) [input_a] + [output_abc]?
I am open to all suggestions, pointing directions, help.
(function() { function calcABC(input_a, input_b, input_c) { input_a = parseFloat(input_a); input_b = parseFloat(input_b); input_c = parseFloat(input_c); return (input_a + input_b + input_c).toFixed(1); } var SUM_ABC = document.getElementById("FORMINPUT"); if (SUM_ABC) { SUM_ABC.onsubmit = function() { this.output_abc.value = calcABC(this.input_a.value, this.input_b.value, this.input_c.value); return false; }; } }());
<form id="FORMINPUT" action=""> <p><label for="input_a">input a</label> <input id="input_a" name="input_a" type="number" pattern="[1-9]" min="1" max="99" /></p> <p><label for="input_b">input b</label> <input id="input_b" name="input_b" type="number" pattern="[1-9]" min="1" max="99" /></p> <p><label for="input_c">input c</label> <input id="input_c" name="input_c" type="number" pattern="[1-9]" min="1" max="99" /></p> <p><input type="reset" value="Reset" /> <input type="submit" value="Calculate" /></p> <p><label for="output_abc">output abc</label> <output id="output abc" name="output abc" type="number"></output> </p> <p>Here I want to display [input_a + output_abc]</p> </form>
What you can do is round your ouput_abc as
Math.round(output.abc * 2)/2
It will give you the output in 0.5 steps
Rounding to 0.5, is very similar to rounding say to 2 decimal places etc.
Basically multiple by X, round, and then divide by X..
X = to the rounding spec. So if you wanted to round to 1 decimal place for example -> 7.17 = Math.round(7.17 * 10) / 10
, this would of course give you 7.2
So to round by 0.5
, X will just equal 2..
eg.
Math.round(7.7 * 2) / 2 === 7.5
Maybe you can add after the line where you are calling the calcABC function but before that assign the return value from the function to a variable.
function calcABC(input_a, input_b, input_c) {
input_a = parseFloat(input_a);
input_b = parseFloat(input_b);
input_c = parseFloat(input_c);
return (input_a + input_b + input_c).toFixed(1);
}
var SUM_ABC = document.getElementById("FORMINPUT");
if (SUM_ABC) {
SUM_ABC.onsubmit = function() {
var outputValue = calcABC(this.input_a.value, this.input_b.value, this.input_c.value);
this.output_abc.value = Math.round(outputValue * 2)/2
return false;
};
}
}());````
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.