Colin Sygiel
Colin Sygiel

Reputation: 945

javascript: How can I round a number to the nearest 10 cents?

I want to round '189.46' to 189.5

Here's an example if we are starting with the number as a string. Can someone please tell me why my method isn't working and what the correct way to do it is?

Math.round(parseFloat('189.46')).toFixed(1);

Upvotes: 3

Views: 1867

Answers (2)

gavgrif
gavgrif

Reputation: 15509

Multiply the number by 10 and round that (using the provided 189.46 - this will give 1895), and then divide by 10 to return to a decimal number( in this example 189.5).

Assuming that you are requiring this to take a value from an input - rather than a hard coded string / number - I have provided an input to enter the value and a button that triggers the rounding function on the click event.

I have also just put in a small basic number check to ensure that the inputted value is a number (note that all inputs will yield a string) but to check simply if a number has been put in - after parsing it using parseFloat - multiply it by 1 and compare the new value to the inputted value - if its not the same - its not a number.

I also popped in a method of clearing the text description as well when a new value is to be entered into the input box - jus cos' :)

function roundNumber(){
  var num = parseFloat(document.getElementById('numberInput').value);
  if(num * 1 !== num) {
    document.getElementById('numberDisplay').innerText = 'Not a Valid Number - try again';
    document.getElementById('numberInput').value = '';
  } else {
   var numRounded = (Math.round(num*10)/10).toFixed(1);
   document.getElementById('numberDisplay').innerText = 'Rounded number:   '+ numRounded;
   }
}

function clearText(){
  document.getElementById('numberInput').value = '';
  document.getElementById('numberDisplay').innerText = '';
 }
<input type="text" id="numberInput" onclick="clearText()"/>
<button type = "button" id="inputButton" onclick="roundNumber()">Round Value</button>
<p id = "numberDisplay"><p>

Upvotes: 2

JoeCodeman.com
JoeCodeman.com

Reputation: 19

JavaScript's Math object provides a method for rounding to whole numbers.

One of the most common solutions for rounding to a decimal place is to use... Number.prototype.toFixed()

So... try this: `

var x = '189.46';
var k = parseFloat(x).toFixed(1);  //k = 189.5  
var y = parseFloat(k); //y = 189.5 
//typeof(k) = string
//typeof(y) = number

`

Upvotes: 0

Related Questions