71551

Javascript, weird floating point number endless decimal?

Question:

I need some help with floating point numbers...please!

Here's the thing, I have code like below:

<script> function add() { document.getElementById("answer").value = parseFloat(document.getElementById("num1").value) + parseFloat(document.getElementById("num2").value); } function subtract() { document.getElementById("answer").value = parseFloat(document.getElementById("num1").value) - parseFloat(document.getElementById("num2").value); } function multiply() { document.getElementById("answer").value = parseFloat(document.getElementById("num1").value) * parseFloat(document.getElementById("num2").value); } function divide() { document.getElementById("answer").value = parseFloat(document.getElementById("num1").value) / parseFloat(document.getElementById("num2").value); } </script>

Sorry it's a bit long! And then the html is pretty simple:

Calculator

<h3>Enter a value in each box below, then click an operation</h3> <form id="calculatorForm"> <input id="num1" value="0" type="text"> <input id="num2" value="0" type="text"> <br> <input value="+" onclick="add();" type="button"> <input value="-" onclick="subtract();" type="button"> <input value="*" onclick="multiply();" type="button"> <input value="/" onclick="divide();" type="button"> <br> <input id="answer" value="0" type="text"> </form>

You can pretty much guess what my question is gonna be: when I multiply, divide, or subtract two floating point numbers, I end up with an infinite decimal.

I need a quick solution that will round those numbers to two decimal points, and I need it to work later on, because I then need to implement Fahrenheit-to-Celsisus operations afterwards.

I don't care how this is done, but it <strong>must</strong> be Javascript. Sorry if this has been answered before, but I really need an answer soon! Thanks!

EDIT: <strong>A BIG Thankyou to the helpful people who answered my questions. Thank you!</strong>

Answer1:

Use .toFixed():

var num = 45.34343434343; num = num.toFixed(2); // "45.34"

Answer2:

Use the .toFixed() function in Javascript.

document.getElementById("answer").value = (parseFloat(document.getElementById("num1").value) - parseFloat(document.getElementById("num2").value)).toFixed(2);

Or an easier to see version:

var x = 3.14159265358979323; alert(x.toFixed(2)); // 3.14

A very good description of how it works <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed" rel="nofollow">on MDN</a>.

Answer3:

See here there is a function Number.toFixed(num) that do just that.

See more info and other options at <a href="http://www.w3schools.com/jsref/jsref_obj_number.asp" rel="nofollow">W3Schools JS Numbers</a>.

That problem occurs because in Javascript every Number is 64bit floating-point, there no such thing as an Integer.

Answer4:

The .toFixed() is useful, but be ware that correctly rounding number in Javascript (and many other languages) require more work.

There are different rounding rules for "Tie-Breaking" and you need to know what is the one you need because they are used in different scenarios. Look <a href="http://en.wikipedia.org/wiki/Rounding" rel="nofollow">here</a>.

Recommend

  • Special Characters in Google Calculator
  • font-face not showing up on Firefox
  • Use Greasemonkey to remove table
  • AngularJS error injector modulerr
  • Taking input from user and returning an answer in TKinter
  • Store a sequence of specific class types in Scala?
  • How can I have equal heights for inner elements of flexbox grid/boxes/cards without using jQuery?
  • What is the default HTTP verb in WebApi ? GET or POST?
  • (Tcl/Expect) clear screen after exit
  • Scanner nextInt() and hasNextInt() problems
  • Click on button in another program - FindWindow, C#
  • jQuery: How to AJAXify WordPress Search?
  • TFS 2015 - Waiting for an agent to be requested
  • How to synchronize jQuery dialog box to act like alert() of Javascript
  • Trying to get the char code of ENTER key
  • Object and struct member access and address offset calculation
  • Keep this build forever option - Jenkins
  • dc-js disable selecting slices on click for pie chart
  • Meteor: Do Something On Email Verification Confirmation
  • How to clear text inside text field when radio button is select
  • FFmpeg Conversion Error
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • Why ng-show works with ng-repeat but ng-if doesn't? [duplicate]
  • what is the difference between the asp.net mvc application and asp.net web application
  • jquery mobile loadPage not working
  • jQuery tmpl and DataLink beta
  • Data Validation Drop Down Box Arrow Disappearing
  • Matrix multiplication with MKL
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • SQL merge duplicate rows and join values that are different
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Proper way to use connect-multiparty with express.js?
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • How to set the response of a form post action to a iframe source?
  • How do you join a server to an Active Directory (domain)?
  • How do I configure my settings file to work with unit tests?
  • How to stop GridView from loading again when I press back button?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Binding checkboxes to object values in AngularJs