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.

```
var num = 34.7654;
num = Math.round(num * 10) / 10;
console.log(num); // Logs: 34.8
```

```
var number = 123.456;
console.log(number.toFixed(1)); // should round to 123.5
```

`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!
```

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.

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.

If you use `Math.round`

then you will return `5`

in case of `5.01`

, and not `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);
}
```

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;
}
```

x = number, n = decimal-places:

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

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
```

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)
```

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.

`Math.round( num * 10) / 10`

doesn't work.

For example, `1455581777.8-145558160.4`

gives you `1310023617.3999999`

.

So only use `num.toFixed(1)`

`lodash`

has a `round`

method:

`_.round( 4.006, 1 ); // 4.1`

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}}
```

:)

Similar Questions

If I do use a big integer in substr: use BigInt; $acct_hash = substr(('99999999999912345' + $data[1]),0,15); why is the result still 9.9999999999912? I was expecting 999999999999912. Is there somethi

I have a value like 1724.1000000000001,How can I round up values like such to 1724.11 in javascript? I need a generic function.Please help...

I am using JavaScript to create a very simple code that inserts bulletin board codes into a textarea when you click on a button. The code I wrote works ok, however, I would like to be able to place th

I have a bit of javascript that's working well for me, I'd just like it to keep 2 decimal places instead of hiding the extra decimal place if its 0. Right now it says: 0.2 and I'd like it to say: 0

On a report I have the following code for a field: =Sum([PartQty]*[ModuleQty]) Example results are 2.1 and 2.6. What I need is for these value to round up to the value of 3. How can I change my field

I want to round 5.29 to 5.30, 5.14 to 5.15 how to do that I have tried this many ways but not working Not working codes; <?php echo round(5.29, 2); echo round((5.29*100)/100, 2); ?> please some

I have a System.Decimal number 0.00123456789 and I wish to round to 3 significant figures. I expect 0.00123 with the behaviour to be a rounding behaviour rather than truncation. Is there a bullet proo

How do I round an NSNumber to zero decimal spaces, in the following line it seems to keep the decimal spaces: NSNumber holidayNightCount = [NSNumber numberWithDouble:sHolidayDuration.value];

I'm trying to force a float to round up to the 2nd decimal place. I know this isn't the best practice, but it's what I need for a program I'm working on. So for example: 100.00 = 100.00 100.001 = 100.

This question already has an answer here: How to round a number to n decimal places in Java 16 answers While there are many rounding questions answered in StackO., I could not quite translate t

How do you convert between hexadecimal numbers and decimal numbers in C#?

I'm making a calculation and I'm getting 12,443. I want to round it to 12,40. This is the way I'm trying to do it but I'm getting 12 instead of 12,40 float result = Math.round( (new Float(result1)*0.3

I noticed that some of name entries, like O'Rourke or O'reilly breaks javascript in some cases. I wonder how you deal with it. I pull these names out of PHP/MYSQL and put them in javascript. Do you re

I'm using the code below to convert the file size in bytes (test file is 31718 bytes) to KB (30.974609375 KB) but I want to display this to one decimal place (i.e. 30.9 KB). How would I do this in VB.

Possible Duplicate: Double value to round up in Java I am getting float number as input and I want it to round to 2 digits after decimal point. i.e. for example if I get 18.965518 as input, I want i

In JavaScript, I want to define where the decimal place goes. I can only really show it in example. Lets say the input value is 1234. I want the output to be 123.4. Or, if the input is 12345, I want t

In C# rounding a number is easy: Math.Round(1.23456, 4); // returns 1.2346 However, I want to round a number such that the fractional part of the number rounds to the closest fractional part of a pre

I have a numeric value like 30.6355 that represents money, how to round to 2 decimal places?

For example, given the decimal value 5.66, representing 5 hours and 39 minutes, how would I round this number to 5 hours and 45 minutes (the nearest 15 minute interval), aka 5.75. Similarly, if I had

can i limit the decimal place to 4 in javascript with this type of values? the e is the exponent since im using power of ten values. toFixed() doesn't seem to work. 1.0531436913408342e-7 -5.2657184567

I want to round a decimal number with 4 digit(e.g 4.3333) Is there any code in javascript? I tried the following code var dec=round(4.3234323,4);

How do I convert a decimal to an int?

math 5/2 returns you 2. I want 2.5 how do i manage to get decimal values.

I want to call an ASHX file and pass some query string variables from JavaScript and get the return string into a string in the JavaScript. How would I do this? The ASHX file is already coded to respo

I'm displaying star ratings based on a review, using conditionals like the following: - if page.page_reviews.average('rating') == 5 %p Do something... The problem is... with a 1-5 review system, not

I have a bunch of floats and I want to round them up to the next highest multiple of 10. For example: 10.2 should be 20 10.0 should be 10 16.7 should be 20 94.9 should be 100 I only need it to go fr

I know that when using jQuery you can do $('element').click(); to catch the click event of an HTML element, but how do you do that with plain Javascript?

I'm writing a script that needs to move a wrapping node element around on the page. I find that when I do this, I remove the previously wrapped children. How do I unnest the children of a node, so tha

I need to check if a number entered contain 1.more than two digit after decimal 2.decimal at first place (ex:.2345) 3.decimal at last place (ex:2345.) How to do this using javascript.

I'd like to do something like: string.gsub(/(whatever)/,'\n\1\n') But I don't want whatever to be replaced with the literal \nwhatever\n I want the \n to actually correspond to a new line.

How do I convert 1 1/4 to 1.25? I want to take user input and convert it to the logical numerical equivalent. I say logical because 2 R and R 2 need to be 2(has to do with measuring chiropractic adj

Possible Duplicate: Rails 3. How do display two decimal places in edit form? I know I can use sprintf to limit to two decimal places. When I redisplay the prices in a form or just in a table, somet

I need to round values to exactly 2 decimals, but when I use round() it doesn't work, if the value is 0.4, but I need 0.40. round(0.4232323, 2) = 0.42 bad: round(0.4, 2) = 0.4 How can I solve this?

I'm struggling with how to correctly round the result of a calculation (a double) in c++ to n decimal places. Upon trying the standard approach (multiplying the number by 10^n, using the 'round' funct

I want to know,how to round the double value with eight decimal places in PIG.I saw this post but it is not helping me. Any ideas

I want any items that are rounded such as this: (5.101 * 100).round / 100.0 To be output like this: 5.10 Instead of this: 5.1 How do I do this in Ruby?

I need to do some calculations as follows in JavaScript: If result of a division is 0.02 final result should be 1 If result of a division is 1.2 final result should be 2 If result of a division is 2

This seems horrible inefficient. Can someone give me a better Ruby way. def round_value x = (self.value*10).round/10.0 # rounds to two decimal places r = x.modulo(x.floor) # finds remainder f = x.floo

How do you get the row returned by this SQL query using PHP: SET @r := (SELECT ROUND(RAND() * (SELECT COUNT(*) FROM mytable))); SET @sql := CONCAT('SELECT * FROM mytable LIMIT ', @r, ', 1'); PREPARE s

Given the base 36 number YPAYPA, is there a library function in Java that would convert this to a decimal number?

Hello how do I round the following to two decimal places . echo <div class='quote-results-result'>ex VAT £ . ((($_POST['qtylitres'] * $price ['Price']) + $fuelmargin['margin']) / 1.2) . </

function main() { Hello(); } function Hello() { // How do you find out the caller function is 'main'? } Is there a way to find out the call stack at all?

Just wondering how i could round my code to two decimal places rather than the 10 or so it gives? Thank you in advance. print financial return of outcome 1 =,$+str(out1)

Given a binary tree (with left and right child only), how do you write a recursive function to make it into a simple linked list in-place? (no new data structure should be created. Pseudo code is ok).

I want to display a float as a string while making sure to display at least one decimal place. If there are more decimals I would like those displayed. For example: 1 should be displayed as 1.0 1.2345

Sample Code <cfset b = 5.5566> <cfset c = numberFormat(b,9.99)> <cfdump var=#c#> I need c= 5.55 only. How can I do this ,because numberFormat rounds the number?

How do you debug javascript in Safari on Windows. I've tried google but the only thing that seems to be coming up is Safari Enhancer which is for Mac OS.

I have a class public class Money { public string Currency { get; set; } public decimal Amount { get; set; } } and would like to serialize it to JSON. If I use the JavaScriptSerializer I get {Curren

I have the following javascript code, but when I try to use it on the 3rd line, I get [object HTMLHeadingElement] in the HTML output. How do I take the whole HTML of x and prepend it to y.innerHTML? x

By calculating areas I have a number which I need to display in a strange way. Always display 2 decimal places. Always round up the 2nd decimal place if the 3rd+ decimal places > 0. Examples: 0.5