Unable to round simple javascript calculation - javascript

Currently this code outputs a string in two decimal places and I need it to be rounded to the closest integer. I had a play around with "math.round" but was unable to get it to work. Any assistance on this would be greatly appreciated!
function myFunction() {
var str = document.getElementById("blog-body").innerHTML;
var n = str.match(/(\w+)/g).length;
var x = n / 200;
var y = x.toFixed(2);
document.getElementById("result").innerHTML = y + ' Min |';
}
Thank you

Use toFixed(0)
Rounding to nearest integer: (123.123).toFixed(0) results in 123
(123.89).toFixed(0) results in 124
You can also use Math.round(123.3) results in 123 and Math.round(123.89) results in 124

Related

How to round down decimal number in javascript

I have this decimal number: 1.12346
I now want to keep only 4 decimals but I want to round down so it will return: 1.1234. Now it returns: 1.1235 which is wrong.
Effectively. I want the last 2 numbers: "46" do round down to "4" and not up to "5"
How is this possible to do?
var nums = 1.12346;
nums = MathRound(nums, 4);
console.log(nums);
function MathRound(num, nrdecimals) {
return num.toFixed(nrdecimals);
}
If you're doing this because you need to print/show a value, then we don't need to stay in number land: turn it into a string, and chop it up:
let nums = 1.12346;
// take advantage of the fact that
// bit operations cause 32 bit integer conversion
let intPart = (nums|0);
// then get a number that is _always_ 0.something:
let fraction = nums - intPart ;
// and just cut that off at the known distance.
let chopped = `${fraction}`.substring(2,6);
// then put the integer part back in front.
let finalString = `${intpart}.${chopped}`;
Of course, if you're not doing this for presentation, the question "why do you think you need to do this" (because it invalidates subsequent maths involving this number) should probably be answered first, because helping you do the wrong thing is not actually helping, but making things worse.
I think this will do the trick.
Essentially correcting the round up.
var nums = 1.12346;
nums = MathRound(nums, 4);
console.log(nums);
function MathRound(num, nrdecimals) {
let n = num.toFixed(nrdecimals);
return (n > num) ? n-(1/(Math.pow(10,nrdecimals))) : n;
}
This is the same question as How to round down number 2 decimal places?. You simply need to make the adjustments for additional decimal places.
Math.floor(1.12346 * 10000) / 10000
console.log(Math.floor(1.12346 * 10000) / 10000);
If you want this as a reusable function, you could do:
function MathRound (number, digits) {
var adjust = Math.pow(10, digits); // or 10 ** digits if you don't need to target IE
return Math.floor(number * adjust) / adjust;
}
console.log(MathRound(1.12346, 4));
var nums = 1.12346;
var dec = 10E3;
var intnums = Math.floor(nums * dec);
var trim = intnums / dec;
console.log(trim);
var num = 1.2323232;
converted_num = num.toFixed(2); //upto 2 precision points
o/p : "1.23"
To get the float num :
converted_num = parseFloat(num.toFixed(2));
o/p : 1.23

Need to convert number to currency

Currently using below code for conversion of number to currency. The only issue is if I have 1000 it is giving 1000 instead I need 1k.
Current implementation 1000 - 1000
Need 1000 - 1k
Tried in lot many ways to get it done but unable to resolve.
var number = 12345678910;
var digits = 2;
var suffix = ["", "K.", "M.", "B."];
var nbDigits = parseInt(Math.log(number)/Math.LN10);
var power = nbDigits - nbDigits%3;
var tmp = number/ Math.pow(10, power);
var suffixIndex = Math.min(3, power/3);
var result = "$" + tmp.toFixed(digits) + " " + suffix[suffixIndex];
I got this solution from this link
Just simplify calculation of number of digits:
// From:
var nbDigits = parseInt(Math.log(number)/Math.LN10);
// To:
var nbDigits1 = Math.log10(number);
That'll give you the number of digits, without rounding errors. It does return $1.00 K. for 1000.
Hope this helps!

Using arrays to do basic calculations with negative exponent

I'm trying to write a function which outputs the correct result when multiplying a number by a negative power of ten using arrays and split() method. For example the following expressions get the right result: 1x10^-2 = 0.01 1x10^-4 = 0.0001.
Problem comes when the number's length is superior to the exponent value (note that my code treats num as a string to split it in an array as shown in code bellow :
//var num is treated as a string to be splited inside get_results() function
//exponent is a number
//Try different values for exponent and different lengths for num to reproduce the problem
//for example var num = 1234 and var exponent = 2 will output 1.234 instead of 12.34
var num = '1';
var sign = '-';
var exponent = 2;
var op = 'x10^'+sign+exponent;
var re = get_result(num);
console.log(num+op +' = '+ re);
function get_result(thisNum) {
if (sign == '-') {
var arr = [];
var splitNum = thisNum.split('');
for (var i = 0; i <= exponent-splitNum.length; i++) {
arr.push('0');
}
for (var j = 0; j < splitNum.length; j++) {
arr.push(splitNum[j]);
}
if (exponent > 0) {
arr.splice(1, 0, '.');
}
arr.join('');
}
return arr.join('');
}
Demo here : https://jsfiddle.net/Hal_9100/c7nobmnj/
I tried different approaches to get the right results with different num lengths and exponent values, but nothing I came with worked and I came to the point where I can't think of anything else.
You can see my latest try here : https://jsfiddle.net/Hal_9100/vq1hrru5/
Any idea how I could solve this problem ?
PS: I know most of the rounding errors due to javascript floating point conversion are pretty harmless and can be fixed using toFixed(n) or by using specialized third-party librairies, but my only goal here is to get better at writing pure javascript functions.
I am not sure if you want to keep going with the array approach to a solution, but it seems like this could be solved with using the Math.pow() method that already exists.
function computeExponentExpression ( test ) {
var base;
var multiplier;
var exponent;
test.replace(/^(\d+)(x)(\d+)([^])([-]?\d+)$/, function() {
base = parseInt(arguments[1], 10);
multiplier = parseInt(arguments[3], 10);
exponent = parseInt(arguments[5], 10);
return '';
} );
console.log( base * Math.pow(multiplier, exponent));
}
computeExponentExpression('1x10^-4');
computeExponentExpression('1x10^2');
computeExponentExpression('4x5^3');
The problem is where you push the decimal point .
instead of
arr.splice(1, 0, '.');
try this:
arr.splice(-exponent, 0, '.');
See fiddle: https://jsfiddle.net/free_soul/c7nobmnj/1/

Math.round Rounding Error

I Want to round 1.006 to two decimals expecting 1.01 as output
When i did
var num = 1.006;
alert(Math.round(num,2)); //Outputs 1
alert(num.toFixed(2)); //Output 1.01
Similarly,
var num =1.106;
alert(Math.round(num,2)); //Outputs 1
alert(num.toFixed(2));; //Outputs 1.11
So
Is it safe to use toFixed() every time ?
Is toFixed() cross browser complaint?
Please suggest me.
P.S: I tried searching stack overflow for similar answers, but could not get proper answer.
EDIT:
Why does 1.015 return 1.01 where as 1.045 returns 1.05
var num =1.015;
alert(num.toFixed(2)); //Outputs 1.01
alert(Math.round(num*100)/100); //Outputs 1.01
Where as
var num = 1.045;
alert(num.toFixed(2)); //Outputs 1.04
alert(Math.round(num*100)/100); //Outputs 1.05
Try something like...
Math.round(num*100)/100
1) Multiple the original number by 10^x (10 to the power of x)
2) Apply Math.round() to the result
3) Divide result by 10^x
from: http://www.javascriptkit.com/javatutors/round.shtml
(to round any number to x decimal points)
This formula Math.round(num*100)/100 is not always good. Example
Math.round(0.145*100)/100 = 0.14
this is wrong, we want it to be 0.15
Explanation
The problem is that we have floats like that
0.145 * 100 = 14.499999999999998
step one
so If we round, we need to add a little bit to our product.
0.145 * 100 + 1e-14 = 14.500000000000009
I assume that sometimes the product might be something like 1.000000000000001, but it would not be a problem if we add to it, right?
step two
Calculate how much should we add?
We know float in java script is 17 digits.
let num = 0.145
let a = Math.round(num*100)/100
let b = a.toString().length
let c = 17-b-2
let result = Math.round(num*100 + 0.1**c)/100
console.log(result)
console.log('not - ' + a )
(-2) - is just to be sure we are not falling into the same trap of rounding.
One-liner:
let num = 0.145
let result = Math.round(num*100 + 0.1**(17-2-(Math.round(num*100)/100).toString().length))/100
Extras
Remember, that everything above is true for positive numbers. If you rounding negative number you would need to subtract a little bit. So the very final One-liner would be:
let num = -0.145
let result = Math.round(num*100 + Math.sign(num)*0.1**(17-2-(Math.round(num*100)/100).toString().length))/100
I realize this problem is rather old, but I keep running into it even 5 years after the question has been asked.
A working solution to this rounding problem I know of is to convert the number to a string, get the required precision number and round up or down using math rules.
An example where Math.round provides unexpected rounding and an example of string rounding can be found in the following fiddle:
http://jsfiddle.net/Shinigami84/vwx1yjnr/
function round(number, decimals = 0) {
let strNum = '' + number;
let negCoef = number < 0 ? -1 : 1;
let dotIndex = strNum.indexOf('.');
let start = dotIndex + decimals + 1;
let dec = Number.parseInt(strNum.substring(start, start + 1));
let remainder = dec >= 5 ? 1 / Math.pow(10, decimals) : 0;
let result = Number.parseFloat(strNum.substring(0, start)) + remainder * negCoef;
return result.toFixed(decimals);
}
let num = 0.145;
let precision = 2;
console.log('math round', Math.round(num*Math.pow(10, precision))/Math.pow(10, precision));
// 0.145 rounded down to 0.14 - unexpected result
console.log('string round', round(num, precision));
// 0.145 rounded up to 0.15 - expected result
Math.round doesn't work properly here because 0.145 multiplied by 100 is 14.499999999999998, not 14.5. Thus, Math.round will round it down as if it was 14.4. If you convert it to a string and subtract required digit (5), then round it using standard math rules, you will get an expected result of 0.15 (actually, 0.14 + 0.01 = 0.15000000000000002, use "toFixed" to get a nice, round result).

How divide two numbers in java script

I am facing the issue in division of numbers in java script.
Example:
var x= 2500, var y = 100
alert(x/y)
is showing 25.
I need the answer in 25.00 format. What can I do?
When I divide 2536/100, it gives as expected.
You can try number.toFixed(x)
alert( (x/y).toFixed(2) )
You have to use the toPrecision() method: http://www.w3schools.com/jsref/jsref_toprecision.asp
It's a method defined in Number's prototype.
If you want to dynamically retrieve a float number with a specific precision (in your case 2), you can do de following:
var x = 2500;
var y = 100;
var res = x/y;
var desiredNumberOfDecimals = 2;
var floatRes = res.toPrecision(String(res).length + desiredNumberOfDecimals);
Try doing it this way:
alert((x/y).toFixed(2))
var x = 2500;
var y = 100;
alert( (x/y).toFixed(2) );
is it possible to enter x and y as a dollar amount? ie 25.00 and 1.00? if so then use the parseFloat method.
var x = 25.00
var y = 1.00
alert(parseFloat(x/y));
You need to take a look at number formatting and decimal precision etc.
Look here: http://www.mredkj.com/javascript/nfbasic2.html

Categories