We help IT Professionals succeed at work.

Help with Javascript to round decimal points to 2

253 Views
Last Modified: 2017-03-24
Hi there,

I have a form and a javascript to calculate (Sum and Multiply) two fields and put the amount into two different fields. My problem is that the script shows 4 decimal points where I want it to show only 2 decimal points.

Here is the HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Formula Plugin Example</title>
<link href="https://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
<style>
body { background-color:#f7f7f7;}
.container { margin:150px auto;}
</style>
</head>

<body>
<div id="jquery-script-menu">
<div class="jquery-script-center">

<div class="jquery-script-ads"></div>
<div class="jquery-script-clear"></div>
</div>
</div>
<div class="container">
  <h1>jQuery Formula Plugin Example</h1>
  <hr />
  <form role="form">
    <div class="row">
      <div class="span4">
        <label >Field 1
        </label>
        <input type="text" class="form-control" value="3245.37" data-variavel="field1"   >
      </div>
      <div class="span4">
        <label >Field 2
        </label>
        <input type="text" class="form-control" data-variavel="field2"    >
      </div>
     
      <div class="span4">
        <label >Result = ( #field1# * #field2#)
        </label>
        <input type="text" class="form-control" data-formula="#field1# + #field2#"   >
      </div>
     
      <div class="span4">
        <label >Result = #field1# * #field2#
        </label>
        <input type="text" class="form-control" data-formula="#field1# * #field2#"   >
      </div>
    </div>
 
  </form>
  </div>
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="jquery.formula.js"></script>

</body>
</html>
===========================================
Here is the script:

$(function () {

    // looking for inputs with data-formula attribute
    $("input:text[data-formula]").each(function () {
        var formula = $(this).attr('data-formula');
        var camposEnvolvidos = formula.match(/#([_a-zA-Z0-9]){1,15}#/g); // Search all fields in default # FIELD #
        var campoAtual = $(this);
        var formulaInicial = formula;

        $.each(camposEnvolvidos, function (key, nome) {
            var campoEnvolvido = $("[data-variavel ='" + nome.replace('#', '').replace('#', '') + "'")[0];//Name of the variable involved
            if (!campoEnvolvido)
                return;

            $(campoEnvolvido).bind('input', function () {//Binds one or more related functions
                var formulaFinal = formulaInicial;
                $.each(camposEnvolvidos, function (keycampo, nomeCampo) {
                    formulaFinal = formulaFinal.replace(nomeCampo, $("[data-variavel ='" + nomeCampo.replace('#', '').replace('#', '') + "'").val().replace(",", "."));
                });
                try {
                    if (camposEnvolvidos.length > 1)
                        campoAtual.val(eval(formulaFinal).toFixed(4));//Fixes subtraction error of 0.3 - 0.1 = 0,1999999...
                    else
                        campoAtual.val(formulaFinal);

                    var mascara = campoAtual.attr("data-mask");

                    if (mascara != undefined && mascara != "" && campoAtual.mask != undefined) {//Checks whether mascara component is used
                        campoAtual.mask(mascara, {
                            translation: {
                                S: { pattern: /^\-/, optional: true },
                                9: { pattern: /[0-9]/ }
                            }
                        });

                    }
                    campoAtual.trigger('input');//Call the actions associated with it
                } catch (e) {
                    //alert ou
                    campoAtual.val("0");
                }
            });
        });
    });

});
=======================================================
Any ideas?
Comment
Watch Question

Commented:
Have you tried the ToFixed method?
ex.   + value.ToFixed(2)

ToFixed returns a string, to make it a number again, just add a '+' sign ( which results in 0 + value.ToFixed(2) )

Author

Commented:
Where in the code would I do that? Could you give me the correct code to try?
ste5anSenior Developer
CERTIFIED EXPERT

Commented:
What to you want to do?

"Show only two numbers" is a formatting problem, while round means to use different math..

Author

Commented:
The result has 4 decimal points. I want only 2 decimal points.

Author

Commented:
for example 3245.37 x 3 gives me 9736.1100. I want it to return only 2 decimals rather than 4.
Thanks

Commented:
campoAtual.val(eval(formulaFinal).toFixed(4));//Fixes subtraction error of 0.3 - 0.1 = 0,1999999...

--> Try toFixed(2)

Commented:
Change toFixed(4) to toFixed(2) in your code

if (camposEnvolvidos.length > 1)
            campoAtual.val(eval(formulaFinal).toFixed(2));//Fixes subtraction error of 0.3 - 0.1 = 0,1999999...
else
            campoAtual.val(formulaFinal);

Open in new window

Author

Commented:
Changed .toFixed(4 ) to .toFixed(2) and still shows 4 decimals.
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
ste5anSenior Developer
CERTIFIED EXPERT

Commented:
The most precise rounding is found at Mozilla.

Be aware that math in JavaScript is problematic, as already Thomas pointed out, you often work with strings, which can produce different results than numbers.

Author

Commented:
I did it and still no go. Is there a way to do it to the form itself?

Commented:
I tried using your code in JSFiddle.
Changing .ToFixed(4) -> .ToFixed(2) did work !
So please be sure you run the latest version of your code.

Author

Commented:
Used the suggested solution and made a simple code change and it worked.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.