Javascript – Add Float numbers upto 2 Decimal

Hi,

Today I was creating a page that is basically a calculator page have many text fields. All of them can accept number upto 2 decimal and onBlur() I have to total that numbers and display on the page

 <script language="JavaScript" type="text/javascript">

function something()
{
    var val = parseFloat('2.22') + parseFloat('3.33');
    val = parseInt( val * 100 ) / 100;
    alert(val)

}

</script>

it results 5.5500000000000001 but my expected result was 5.55

After making a little tweak I am able to get my desired result

<script language="JavaScript" type="text/javascript">
function something()
{
    var val = parseFloat('2.22') + parseFloat('3.33');
    val = parseInt( val * 100 ) / 100;
   
    alert(val)
}
</script>

I hope this helps you 🙂 

Leave a Reply

Your email address will not be published. Required fields are marked *