I want to divide a number in JavaScript and it would return a decimal value.
For example: 737/1070 - I want JavaScript to return 0.68; however it keeps rounding it off and return it as 0.
How do I set it to return me either two decimals place or the full results?
Make one of those numbers a float.
737/parseFloat(1070)
or a bit faster:
737*1.0/1070
convert to 2 decimal places
Math.round(737 * 100.0 / 1070) / 100
(737/1070).toFixed(2); rounds the result to 2 decimals and returns it as a string. In this case the rounded result is 0.69 by the way, not 0.68. If you need a real float rounded to 2 decimals from your division, use parseFloat((737/1070).toFixed(2))
See also
Also you can to use [.toPrecision(n)], where n is (total) the number of digits. So (23.467543).toPrecision(4) => 23.47 or (1241876.2341).toPrecision(8) => 1241876.2.
See MDN
Try this
let ans = 737/1070;
console.log(ans.toFixed(2));
toFixed() function will do
to get it to 2 decimal places you can: alert( Math.round( 737 / 1070 * 100) / 100 )
with lodash:
const _ = require("lodash");
Use of _.divide() method
let gfg = _.divide(12, 5);
Printing the output
console.log(gfg)
2.4
credit
Related
I use this way to divide a decimal.I want to divide this number by 100.
var myNumber="1245.6699";
myNumber=""+parseFloat(myNumber)*10000/1000000;//"12.4566990000000002"
myNumber=Number(myNumber);//12.4566990000000002
I want this division to keep 6 digit decimal like this 12.456699,but now the result is 12.4566990000000002,how to modify?
Use toFixed() method of Number object:
var myNumber = "1245.6699";
console.log(
(myNumber / 100).toFixed(6)
)
I have this :
i=4.568;
document.write(i.toFixed(2));
output :
4.57
But i don't want to round the last number to 7 , what can i do?
Use simple math instead;
document.write(Math.floor(i * 100) / 100);
(jsFiddle)
You can stick it in your own function for reuse;
function myToFixed(i, digits) {
var pow = Math.pow(10, digits);
return Math.floor(i * pow) / pow;
}
document.write(myToFixed(i, 2));
(jsFiddle)
Just cut the longer string:
i.toFixed(3).replace(/\.(\d\d)\d?$/, '.$1')
A slightly convoluted approach:
var i=4.568,
iToString = i + '';
i = parseFloat(iToString.match(/\d+\.\d{2}/));
console.log(i);
This effectively takes the variable i and converts it to a string, and then uses a regex to match the numbers before the decimal point and the two following that decimal point, using parseFloat() to then convert it back to a number.
References:
match()
parseFloat().
Regular Expressions.
I need to round off the decimal value to decimal places using javascript.
Ex,:
16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19
I have found some answers, but most of them do not round off 16.185 to 16.19..
(Math.round((16.185*Math.pow(10,2)).toFixed(1))/Math.pow(10,2)).toFixed(2);
If your value is, for example 16.199 normal round will return 16.2... but with this method youll get last 0 too, so you see 16.20! But keep in mind that the value will returned as string. If you want to use it for further operations, you have to parsefloat it :)
And now as function:
function trueRound(value, digits){
return (Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits);
}
Thanks #ayk for your answer, I modified your function into this :
function trueRound(value, digits){
return ((Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits)) * 1;
}
just add " *1 "
because with yours, as you wrote, 16.2 becomes 16.20
and I don't need the zero in the back.
Use-
Decimal ds=new Decimal(##.##);
String value=ds.format(inputnumber);
This will work perfectly in my case ,hope it will work 100%
The code you are using for rounding off is correct. But to get the desired result please remove the .toFixed(numOfDec) from the code.
The function:
function formatNumber(myNum, numOfDec) {
var decimal = 1
for (i = 1; i <= numOfDec; i++)
decimal = decimal * 10 //The value of decimal determines the number of decimals to be rounded off with (.5) up rule
var myFormattedNum = Math.round(myNum * decimal) / decimal
return (myFormattedNum)
}
Hope it helps you in some way :)
function formatNumber(myNum, numOfDec) {
var dec = Math.pow(10, numOfDec);
return Math.round(myNum * dec + 0.1) / dec;
}
parseFloat(myNum.toFixed(numOfDec))
[EDIT]
This code does not work for a value like 18.185, as 18.185 * Math.pow(10,2) is being evaluated to 1818.4999999999997
Math.round(<value> * Math.pow(10,<no_of_decimal_places>)) / Math.pow(10,<no_of_decimal_places>) ;
Example:
1234.5678 --> 2 decimal places --> 1234.57
Math.round(1234.5678 * Math.pow(10,2)) / Math.pow(10,2) ;
You COULD try a simpler function...
function roundOffTo(number, place) {
return Math.round(number * place) / place;
}
How does it work?
The place can be 10, 100, 1000, 10000, and so on. The reverse will be 0.1, 0.01, 0.001, and so on. Let's say your number is 16.185, and your place is 100. The first thing it'll do is to multiply the number by the place, which is 1618.5. Rounding it off by Math.round will result in 1619. Dividing by the place gives us 16.19. There.
By the way, no need to worry about the .5 problem today, it's kinda fixed. But just in case it isn't, change Math.round(number * place) to Math.round(number * place + 0.1).
I wanted to display a number to 2 decimal places.
I thought I could use toPrecision(2) in JavaScript .
However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.
See it on JSbin.
What is the best way to do this?
I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?
float_num.toFixed(2);
Note:toFixed() will round or pad with zeros if necessary to meet the specified length.
You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.
number.parseFloat(2) works but it returns a string.
If you'd like to preserve it as a number type you can use:
Math.round(number * 100) / 100
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
with toFixed you can set length of decimal points like this:
let number = 6.1234
number.toFixed(2) // '6.12'
but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.
let number = 6
number.toFixed(2) // '6.00'
to avoid this you have to convert the result to a number. you can do this with these two methods:
let number1 = 6
let number2 = 6.1234
// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12
// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12
Try toFixed instead of toPrecision.
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // return 1.01
round(1.004, 2); // return 1 instead of 1.00
The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/
I used this way if you need 2 digits and not string type.
const exFloat = 3.14159265359;
console.log(parseFloat(exFloat.toFixed(2)));
You could try mixing Number() and toFixed().
Have your target number converted to a nice string with X digits then convert the formated string to a number.
Number( (myVar).toFixed(2) )
See example below:
var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
$('#message').text( myNumber * multiplier );
});
$('#actionButton2').on('click', function() {
$('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>
<div id="message"></div>
The toFixed() method formats a number using fixed-point notation.
and here is the syntax
numObj.toFixed([digits])
digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using
numObj.toFixed([digits]) * 1
It also can throws exceptions like TypeError, RangeError
Here is the full detail and compatibility in the browser.
let a = 0.0500
a.toFixed(2);
//output
0.05
There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.
Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');
Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:
Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)
float_num = parseFloat(float_num.toFixed(2))
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}
Am I missing something here?
var someNumber = 123.456;
someNumber = someNumber.toFixed(2);
alert(typeof(someNumber));
//alerts string
Why does .toFixed() return a string?
I want to round the number to 2 decimal digits.
Number.prototype.toFixed is a function designed to format a number before printing it out. It's from the family of toString, toExponential and toPrecision.
To round a number, you would do this:
someNumber = 42.008;
someNumber = Math.round( someNumber * 1e2 ) / 1e2;
someNumber === 42.01;
// if you need 3 digits, replace 1e2 with 1e3 etc.
// or just copypaste this function to your code:
function toFixedNumber(num, digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(num*pow) / pow;
}
.
Or if you want a “native-like” function, you can extend the prototype:
Number.prototype.toFixedNumber = function(digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(this*pow) / pow;
}
someNumber = 42.008;
someNumber = someNumber.toFixedNumber(2);
someNumber === 42.01;
//or even hexadecimal
someNumber = 0xAF309/256; //which is af3.09
someNumber = someNumber.toFixedNumber(1, 16);
someNumber.toString(16) === "af3.1";
However, bear in mind that polluting the prototype is considered bad when you're writing a module, as modules shouldn't have any side effects. So, for a module, use the first function.
I've solved this problem by changing this:
someNumber = someNumber.toFixed(2)
...to this:
someNumber = +someNumber.toFixed(2);
However this will convert the number to a string and parse it again, which will have a significant impact on performance. If you care about performance or type safety, check the the other answers as well.
It returns a string because 0.1, and powers thereof (which are used to display decimal fractions), are not representable (at least not with full accuracy) in binary floating-point systems.
For example, 0.1 is really 0.1000000000000000055511151231257827021181583404541015625, and 0.01 is really 0.01000000000000000020816681711721685132943093776702880859375. (Thanks to BigDecimal for proving my point. :-P)
Therefore (absent a decimal floating point or rational number type), outputting it as a string is the only way to get it trimmed to exactly the precision required for display.
Why not use parseFloat?
var someNumber = 123.456;
someNumber = parseFloat(someNumber.toFixed(2));
alert(typeof(someNumber));
//alerts number
I solved it with converting it back to number using JavaScript's Number() function
var x = 2.2873424;
x = Number(x.toFixed(2));
Of course it returns a string. If you wanted to round the numeric variable you'd use Math.round() instead. The point of toFixed is to format the number with a fixed number of decimal places for display to the user.
You can simply use a '+' to convert the result to a number.
var x = 22.032423;
x = +x.toFixed(2); // x = 22.03
May be too late to answer but you can multiple the output with 1 to convert to number again, here is an example.
const x1 = 1211.1212121;
const x2 = x1.toFixed(2)*1;
console.log(typeof(x2));
What would you expect it to return when it's supposed to format a number ? If you have a number you can't pretty much do anything with it because e.g.2 == 2.0 == 2.00 etc. so it has to be a string.
Because its primary use is displaying numbers? If you want to round numbers, use Math.round() with apropriate factors.
To supply an example of why it has to be a string:
If you format 1.toFixed(2) you would get '1.00'.
This is not the same as 1, as 1 does not have 2 decimals.
I know JavaScript isn't exactly a performance language, but chances are you'd get better performance for a rounding if you use something like:
roundedValue = Math.round(value * 100) * 0.01
You should use it like below.
var someNumber: number = 0.000000;
someNumber = Number(someNumber.toFixed(2))
Why not * the result by 1 i.e
someNumber.toFixed(2) * 1
Here's a slightly more functional version of the answer m93a provided.
const toFixedNumber = (toFixTo = 2, base = 10) => num => {
const pow = Math.pow(base, toFixTo)
return +(Math.round(num * pow) / pow)
}
const oneNumber = 10.12323223
const result1 = toFixedNumber(2)(oneNumber) // 10.12
const result2 = toFixedNumber(3)(oneNumber) // 10.123
// or using pipeline-operator
const result3 = oneNumber |> toFixedNumber(2) // 10.12
For others like me that happen upon this very old question, a modern solution:
const roundValue = (num, decimals = 2) => {
let scaling = 10 ** decimals;
return Math.round((num + Number.EPSILON) * scaling) / scaling;
}
ref: https://stackoverflow.com/a/11832950
Be careful using toFixed() and Math.round(), they can produce unexpected results due to the floating point number system:
function toFixedNumber(num, digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(num*pow) / pow;
}
console.log(toFixedNumber(130.795, 2, 10));
// 130.79 (incorrect)
console.log(toFixedNumber(100.795, 2, 10));
// 100.8
console.log(+130.795.toFixed(2));
// 130.79 (incorrect)
console.log(+100.795.toFixed(2));
// 100.8
I recommend using Lodash's _.round() function: https://lodash.com/docs/4.17.15#round
_.round(130.795, 2);
// 130.8