By Walker


2011-09-08 03:55:47 8 Comments

Can you round a number in javascript to 1 character after the decimal point (properly rounded)?

I tried the *10, round, /10 but it leaves two decimals at the end of the int.

19 comments

@roy neo 2018-10-31 09:22:06

Math.round( mul/count * 10 ) / 10

Math.round(Math.sqrt(sqD/y) * 10 ) / 10

Thanks

@Lucas Montenegro 2018-07-10 17:11:57

I found a way to avoid the precision problems:

function badRound (num, precision) {
    const x = 10 ** precision;
    return Math.round(num * x) / x
}
// badRound(1.005, 2) --> 1

function round (num, precision) {
    const x = 10 ** (precision + 1);
    const y = 10 ** precision;
    return Math.round(Math.round(num * x) / 10) / y
}
// round(1.005, 2) --> 1.01

@Alberto 2018-06-25 12:58:50

I made one that returns number type and also places decimals only if are needed (no 0 padding).

Examples:

roundWithMaxPrecision(11.234, 2); //11.23
roundWithMaxPrecision(11.234, 1); //11.2
roundWithMaxPrecision(11.234, 4); //11.23
roundWithMaxPrecision(11.234, -1); //10

roundWithMaxPrecision(4.2, 2); //4.2
roundWithMaxPrecision(4.88, 1); //4.9

The code:

function roundWithMaxPrecision (n, precision) {
    return Math.round(n * Math.pow(10, precision)) / Math.pow(10, precision);
}

@atiruz 2013-06-14 22:43:50

Try with this:

var original=28.453

// 1.- round "original" to two decimals
var result = Math.round (original * 100) / 100  //returns 28.45

// 2.- round "original" to 1 decimal
var result = Math.round (original * 10) / 10  //returns 28.5

// 3.- round 8.111111 to 3 decimals
var result = Math.round (8.111111 * 1000) / 1000  //returns 8.111

less complicated and easier to implement...

with this, you can create a function to do:

function RoundAndFix (n, d) {
    var m = Math.pow (10, d);
    return Math.round (n * m) / m;
}

function RoundAndFix (n, d) {
    var m = Math.pow (10, d);
    return Math.round (n * m) / m;
}
console.log (RoundAndFix(8.111111, 3));

EDIT: see this How to round using ROUND HALF UP. Rounding mode that most of us were taught in grade school

@Noyo 2014-12-04 17:56:46

Nope: RoundAndFix(1.005, 2) .

@Amr Ali 2018-02-13 10:43:27

In general, rounding is done by scaling: round(num / p) * p

Using the exponential notation handles rounding of +ve numbers, correctly. However, this method fails to round -ve edge cases correctly.

function round(num, precision = 2) {
	var scaled = Math.round(num + "e" + precision);
	return Number(scaled + "e" + -precision);
}

// testing some edge cases
console.log( round(1.005, 2) );  // 1.01 correct
console.log( round(2.175, 2) );  // 2.18 correct
console.log( round(5.015, 2) );  // 5.02 correct

console.log( round(-1.005, 2) );  // -1    wrong
console.log( round(-2.175, 2) );  // -2.17 wrong
console.log( round(-5.015, 2) );  // -5.01 wrong

Here, also is one function I wrote to do arithmetic rounding, you can test it yourself.

/**
 * MidpointRounding away from zero ('arithmetic' rounding)
 * Uses a half-epsilon for correction. (This offsets IEEE-754
 * half-to-even rounding that was applied at the edge cases).
 */

function RoundCorrect(num, precision = 2) {
	// half epsilon to correct edge cases.
	var c = 0.5 * Number.EPSILON * num;
//	var p = Math.pow(10, precision); //slow
	var p = 1; while (precision--> 0) p *= 10;
	if (num < 0)
		p *= -1;
	return Math.round((num + c) * p) / p;
}

// testing some edge cases
console.log(RoundCorrect(1.005, 2));  // 1.01 correct
console.log(RoundCorrect(2.175, 2));  // 2.18 correct
console.log(RoundCorrect(5.015, 2));  // 5.02 correct

console.log(RoundCorrect(-1.005, 2));  // -1.01 correct
console.log(RoundCorrect(-2.175, 2));  // -2.18 correct
console.log(RoundCorrect(-5.015, 2));  // -5.02 correct

@Koustav Ray 2018-01-24 11:40:15

ES 6 Version of Accepted Answer:

function round(value, precision) {
    const multiplier = 10 ** (precision || 0);
    return Math.round(value * multiplier) / multiplier;
}

@Kevin Leary 2016-03-03 20:30:11

lodash has a round method:

_.round(4.006);
// => 4

_.round(4.006, 2);
// => 4.01

_.round(4060, -2);
// => 4100

Docs.

Source.

@sidonaldson 2016-06-21 14:49:37

Little Angular filter if anyone wants it:

angular.module('filters').filter('decimalPlace', function() {
    return function(num, precision) {
        var multiplier = Math.pow(10, precision || 0);
        return Math.round(num * multiplier) / multiplier;
    };
});

use if via:

{{model.value| decimalPlace}}
{{model.value| decimalPlace:1}}
{{model.value| decimalPlace:2}}

:)

@Billy Moon 2011-09-08 04:06:59

Math.round( num * 10) / 10 works, here is an example...

var number = 12.3456789;
var rounded = Math.round( number * 10 ) / 10;
// rounded is 12.3

if you want it to have one decimal place, even when that would be a 0, then add...

var fixed = rounded.toFixed(1);
// fixed is always to 1dp
// BUT: returns string!

// to get it back to number format
parseFloat( number.toFixed(2) )
// 12.34
// but that will not retain any trailing zeros

// so, just make sure it is the last step before output,
// and use a number format during calculations!

EDIT: add round with precision function...

Using this principle, for reference, here is a handy little round function that takes precision...

function round(value, precision) {
    var multiplier = Math.pow(10, precision || 0);
    return Math.round(value * multiplier) / multiplier;
}

... usage ...

round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7

... defaults to round to nearest whole number (precision 0) ...

round(12345.6789) // 12346

... and can be used to round to nearest 10 or 100 etc...

round(12345.6789, -1) // 12350
round(12345.6789, -2) // 12300

... and correct handling of negative numbers ...

round(-123.45, 1) // -123.4
round(123.45, 1) // 123.5

... and can be combined with toFixed to format consistently as string ...

round(456.7, 2).toFixed(2) // "456.70"

@Cobby 2012-09-14 05:25:37

Be careful using .toFixed() as it returns a string when you maybe want a number.

@Billy Moon 2012-09-14 09:07:48

@Cobby good call - edited!

@Cobby 2012-09-17 01:12:50

Cool, obviously using parseFloat will remove decimals left by .toFixed() if it's a whole number (zeros). Generally, if you want to do the math it's best to follow your first example. If you want to display a number in your UI then use .toFixed().

@Billy Moon 2012-09-17 10:22:02

Hmmm... that makes sense, any way you convert to number must always strip the erroneous zeros, which is why it has to stay a string. I guess it should always be the last step before display, and not used in calculations.

@Wilt 2014-03-04 13:02:28

Be careful using .toFixed() as it might return different rounding results for different browsers. Read this post for details on the topic!

@Nick 2016-11-24 12:34:31

Can I add a zero if no DP are present?

@klodoma 2015-10-29 15:15:56

To complete the Best Answer:

var round = function ( number, precision )
{
    precision = precision || 0;
    return parseFloat( parseFloat( number ).toFixed( precision ) );
}

The input parameter number may "not" always be a number, in this case .toFixed does not exist.

@P.W 2016-02-16 00:20:56

Math.round( num * 10) / 10 doesn't work.

For example, 1455581777.8-145558160.4 gives you 1310023617.3999999.

So only use num.toFixed(1)

@Jasper de Vries 2012-10-02 21:04:08

If you use Math.round(5.01) you will get 5 instead of 5.0.

If you use toFixed you run into rounding issues.

If you want the best of both worlds combine the two:

(Math.round(5.01 * 10) / 10).toFixed(1)

You might want to create a function for this:

function roundedToFixed(_float, _digits){
  var rounder = Math.pow(10, _digits);
  return (Math.round(_float * rounder) / rounder).toFixed(_digits);
}

@jsNovice 2015-02-23 09:50:18

If you care about proper rounding up then:

function roundNumericStrings(str , numOfDecPlacesRequired){ 
     var roundFactor = Math.pow(10, numOfDecPlacesRequired);  
     return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString();  }

Else if you don't then you already have a reply from previous posts

str.slice(0, -1)

@Ege Özcan 2015-02-10 13:41:49

This seems to work reliably across anything I throw at it:

function round(val, multiplesOf) {
  var s = 1 / multiplesOf;
  var res = Math.ceil(val*s)/s;
  res = res < val ? res + multiplesOf: res;
  var afterZero = multiplesOf.toString().split(".")[1];
  return parseFloat(res.toFixed(afterZero ? afterZero.length : 0));
}

It rounds up, so you may need to modify it according to use case. This should work:

console.log(round(10.01, 1)); //outputs 11
console.log(round(10.01, 0.1)); //outputs 10.1

@super 2014-02-12 14:54:39

x = number, n = decimal-places:

function round(x, n) {
    return Math.round(x * Math.pow(10, n)) / Math.pow(10, n)
}

@Noyo 2014-12-04 17:56:20

Nope: round(1.005, 2) .

@Joseph Silber 2011-09-08 04:01:23

var num = 34.7654;

num = Math.round(num * 10) / 10;

console.log(num); // Logs: 34.8

@jimbo 2011-09-08 04:40:29

I vote for toFixed(), but, for the record, here's another way that uses bit shifting to cast the number to an int. So, it always rounds towards zero (down for positive numbers, up for negatives).

var rounded = ((num * 10) << 0) * 0.1;

But hey, since there are no function calls, it's wicked fast. :)

And here's one that uses string matching:

var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');

I don't recommend using the string variant, just sayin.

@jagbandhuster 2011-09-08 04:17:38

If your method does not work, plz post your code.

However,you could accomplish the rounding off task as:

var value = Math.round(234.567*100)/100

Will give you 234.56

Similarly

 var value = Math.round(234.567*10)/10

Will give 234.5

In this way you can use a variable in the place of the constant as used above.

@Pablo Fernandez 2011-09-08 04:05:24

var number = 123.456;

console.log(number.toFixed(1)); // should round to 123.5

@jimbo 2011-09-08 04:29:48

Good call on toFixed() - I learned something today :)

@Hamish Grubijan 2013-04-25 21:45:18

Sometimes toFixed() has glitches - I have seen it in a Chrome browser where I call toFixed(), then convert to a string, and it shows something like 10.00000000068 - weird. Cannot reproduce this reliably though.

@Noyo 2014-12-04 17:59:54

@Dalibor 2015-06-30 07:43:52

Yes, I accountered glitches with toFixed() even with just few decimals. It rounded fraction 4 to the next higher number instead of lower, if I recall correctly.

@Ricardo 2019-05-25 00:41:34

as mentioned by @cobby above: be careful using .toFixed() as it returns a String when you maybe want a Number

Related Questions

Sponsored Content

65 Answered Questions

[SOLVED] Round to at most 2 decimal places (only if necessary)

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

38 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5720364 View
  • 7117 Score
  • 79 Answer
  • Tags:   javascript arrays

54 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

48 Answered Questions

[SOLVED] Validate decimal numbers in JavaScript - IsNumeric()

29 Answered Questions

[SOLVED] How to round a number to n decimal places in Java

Sponsored Content