开发者

Make calculation include decimals

开发者 https://www.devze.com 2023-03-25 02:54 出处:网络
I am new to Javascript and I got most of this code from another Q&A on this site worked great! Only problem is that the code doesn\'t count the decimals! How do I get this code to count the decima

I am new to Javascript and I got most of this code from another Q&A on this site worked great! Only problem is that the code doesn't count the decimals! How do I get this code to count the decimals?

<table> <tr class=r1> 
<th class=d1>1-24</th> 
<th class=d2>25-49</th> 
<th class=d2>50-99</th> 
<th class=d2>100-499</th> 
<th class=d2>500 = Offert</th> 
        <tr class=r1> 
        <td class=d1 id=A>99,00:-</td> 
        <td class=d2 id=B></td> 
        <开发者_如何学C;td class=d2 id=C></td> 
        <td class=d2 id=D></td> 
        <td class=d2> </td> </tr>
</table>

That's the table I have to make a bracket price.

This is the Javascript:

(function(){
// put all your JavaScript in a closure so you don't pollute the global namespace
  function extract_float_from_price ( price ) {
    return parseFloat( price.replace(/\:*-/,'') );
  }

  function evaluate_savings ( ) {
    var A = extract_float_from_price( $('#A').text() );

    $('#B').text( parseInt(A * 0.96 ) + ':-' );
        $('#C').text( parseInt(A * 0.92 ) + ':-' );
        $('#D').text( parseInt(A * 0.88 ) + ':-' );
  }

  $( evaluate_savings ); // binds to Dom Ready
})()

Please help me get the code to show decimals for a more exact price.


Something to learn immediately, so you get better responses in future, this is JavaScript not Java. They look similar, but are by no means the same. There are plenty of discussions on the Internet describing the differences.

In answer to your question, try the JavaScript function parseFloat instead of parseInt.


You need to do two things

  • use parseFloat
  • replace , with . as . is the comma separator in javascript.

So,

// get the part of the text that should be parsed
var A = /[\d,.]+/.exec($('#A').text())[0];

// replace any , with .
A = A.replace(",",".")

// parse the string into a Number
A = A.parseFloat(A, 10);

// output the result
$('#B').text( (A * 0.96)  + ':-' );

should work for you


Use parseFloat rather than parseInt in the following statements

    $('#B').text( parseFloat(A * 0.96 ) + ':-' );
    $('#C').text( parseFloat(A * 0.92 ) + ':-' );
    $('#D').text( parseFloat(A * 0.88 ) + ':-' );

BTW, it is great that some answer helped you do something, but you should also try to understand what the code does and how it does when you use it.

And, Java != Javascript

Update:

To round a number use toFixed. You might want to do:

$('#B').text( parseFloat(A * 0.96 ).toFixed(2) + ':-' );

and so on

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号