bantandor
bantandor

Reputation: 267

How do I get Math floor function working in math addition problem

I have a problem getting Math.floor function add numbers.

    <script type="text/javascript">

    function getOrt(){
        
        var bir = document.getElementById('bir').value;
        var iki = document.getElementById('iki').value;
        var uc = document.getElementById('uc').value;
        var avrg = Math.floor(bir+iki+uc);
        document.getElementById('avrg').value=avrg;
        }

</script>

if I enter the value of 1 for bir, 2 for iki and 3 for uc, I get 123

In the html part

<div class="form-group">
                    <div class="form-row form-row-1">
                        <input type="text" name="bir" class="bir" id="bir" placeholder="bir">
                    </div>
                    
                    <div class="form-row form-row-1">
                        <input type="text" name="iki" class="iki" id="iki" placeholder="iki" >
                    </div>
                    
                    <div class="form-row form-row-1">
                        <input type="text" name="uc" class="uc" id="uc" onchange="getOrt();" placeholder="uc" >
                    </div>
                    <div class="form-row form-row-1">
                        <input type="text" name="ort" class="ort" id="avrg"  placeholder="Ort." >
                    </div>
                    
                </div>

the interesting thing is if I multiple all three number It works

Upvotes: 0

Views: 214

Answers (1)

phuzi
phuzi

Reputation: 13060

bir, iki & uc are all string values. the result of bir+iki+uc is also a string that will not represent the value you think it should.

Since you are using Math.floor then I presume these should/could be floating point values and you should use parseFloat to convert them to floating point number values first.

    var bir = parseFloat(document.getElementById('bir').value);
    var iki = parseFloat(document.getElementById('iki').value);
    var uc = parseFloat(document.getElementById('uc').value);
    // bir, iki and uc are all numbers now
    var avrg = Math.floor(bir+iki+uc);

Upvotes: 4

Related Questions