How to disregard remainder or decimal values:
Example: var x = 5/2;
Result: x = 2.5;
What i want is that whatever decimal value will be disregarded so the final output should be x = 2;
You could use Math.floor() (round down), Math.ceil() (round up) or Math.round() (round to nearest integer), dependening on how you wanted to remove the decimal.
Example:
if x = 2.5, Math.floor(x) = 2, Math.ceil(x) = 3, Math.round(x) = 3.
For Reference:
Check the fiddle http://jsfiddle.net/BVYDR/
The | operator forces its argument to an integral value by rounding towards zero.
(3.141592654 | 0) === 3
parseInt(5/2) will give you 2
Related
How to verify if an input type number contains a maximum of 3 decimals, without using regex?
let x = 1.5555
let y = 1.55
x is false
y is true
You can use a formula like:
(x * 10**N) % 1 === 0
Here x is your number that potentially contains decimals (eg: 1.555) and N is the maximum amount of decimal places you want to allow for.
Eg, for numbers with 3 (N = 3) or fewer decimal places, you will get x*1000, which will evaluate to an integer. Eg:
1.55 -> 1550
1.555 -> 1555
For numbers with more than 3 decimal places, doing x*1000 won't convert it to an int, it will only shift parts of the number over:
1.5555 -> 1555.5 // still a decimal
The % 1 check then gets the remainder of the above number if it was to be divided by 1. If the remainder is 0, then the number was converted to an integer, if it is more than 0, then x*1000 failed to convert the number to an int, meaning that it has more than 3 decimals:
const validate = (x, N) => (x * 10**N) % 1 === 0;
console.log(validate(1.5555, 3)); // false
console.log(validate(1.55, 3)); // true
console.log(validate(1.555, 3)); // true
console.log(validate(0.00000001, 3)); // false
You can convert to string using the toString() method, then split at the point . with the .split() method this will result in an array.
The first element in the array is a string containing the whole number part which is not interesting here for us.
The second element at indice 1 in the resulting array is the decimal part as string.
Now you can check the length property of this string if it is equal or less then three which means it has three or less decimal numbers then we return true in the validation function when not we return false.
const x = 1.5555;
const y = 1.555;
const z = 1.55
function validate(num){
return num.toString().split(".")[1].length <= 3;
}
console.log(validate(x));
console.log(validate(y));
console.log(validate(z));
This may solve your problem
let x = 1.5555;
let y = 1.55;
int length = x.Substring(number.IndexOf(".")).Length;
bool result = length > 3 ? true: false;
I am trying to create a RoundUp function with help of Math.ceil it working fine with positive number but do not round up the negative numbers
Here is what i am trying
var value = -12.369754; --> output = -12
// make value = 12.369754; and out put will be 13
var decimalPoints = 0;
if (decimalPoints == 0) {
value = Math.ceil(parseFloat(value));
}
console.log(value);
Here is the Fiddle http://jsfiddle.net/n7ecyr7h/
Why This function?
I need to create a function in which user will give a number and decimal points upto which he wants to round the number The RoundUp function will roundUp the given value to a given number of decimal points
For example if user enters 12.12445 and wants to roundUp to 3 decimal points the output will be 12.125
Here is a table of required outputs with 2 decimal points
**Input** **output**
1.2369 1.24
1.2869 1.29
-1.1234 -1.13
-1.17321 -1.18
And here is the Updated Fiddle with original JS code http://jsfiddle.net/n7ecyr7h/1/
The Math.ceil method does actually round up even for negative values. The value -12 is the closest integer value that is at higher than -12.369754.
What you are looking for is to round away from zero:
value = value >= 0 ? Math.ceil(value) : Math.floor(value);
Edit:
To use that with different number of decimal points:
// it seems that the value is actually a string
// judging from the parseFloat calls that you have
var value = '-12.369754';
var decimalPoints = 0;
// parse it once
value = parseFloat(value);
// calculate multiplier
var m = Math.pow(10, decimalPoints);
// round the value
value = (value >= 0 ? Math.ceil(value * m) : Math.floor(value * m)) / m;
console.log(value);
Demo: http://jsfiddle.net/Guffa/n7ecyr7h/3/
Math.ceil(-1.1234) will be -1.12 because in negative -1.12 > -1.1234.
I think you misunderstood mathematically.
All my values are being returned from the server as 3 decimal places. I need to round to the nearest 10, 2 decimal places, ex. decimal(18,2) from decimal(18,3). The catch is that when it's a 5, it needs to round down.
I need to do this in JavaScript :D
I can not guarantee 3 decimal places will be returned, that is the maximum.
ex. 4.494 -> 4.49
**ex. 4.495 -> 4.49**
ex. 4.496 -> 4.50
It seems you want special rounding only where the last digit is 5, so test for that and round those cases differently:
function myRound(n) {
// If ends in .nn5, round down
if (/\.\d\d5$/.test(''+n)) {
n = Math.floor(n*100)/100;
}
// Apply normal rounding
return n.toFixed(2);
}
console.log(myRound(4.494)); // 4.49
console.log(myRound(4.495)); // 4.49
console.log(myRound(4.496)); // 4.50
Perhaps create your own custom round function? check out Is it ok to overwrite the default Math.round javascript functionality?
Given the solution in the above post, you might modify it slightly like this:
Number.prototype.round = function(precision) {
var numPrecision = (!precision) ? 0 : parseInt(precision, 10);
var numBig = this * Math.pow(10, numPrecision);
var roundedNum;
if (numBig - Math.floor(numBig) == 0.5)
roundedNum = (Math.round(numBig) + 1) / Math.pow(10, numPrecision);
else
roundedNum = Math.round(numBig) / Math.pow(10, numPrecision);
return roundedNum;
};
var n = 2.344;
var x = n.round(2);
alert(x);
Citing the ECMAScript spec Section 5.2:
The notation “x modulo y” (y must be finite and nonzero) computes a
value k of the same sign as y (or zero) such that abs(k) < abs(y) and
x−k = q × y for some integer q.
so if y is positive, the result k of 'x modulo y' is positive regardless of the sign of x.
and if my understanding is right, ToInt32(-1) equals ToInt32(1)?
The notation x modulo y is used internally within the spec to describe the result of certain operations. So yes, the result k of x modulo y is (by definition) of the same sign as y. It is not claimed that the % operator is equivalent to modulo.
If you're interested, the actual spec for % can be found under section 11.5.3. Interestingly, it makes no use of modulo.
Copy pasting from my previous answer here:
Take a % b
1. When both +ve, Modulo & Remainder are one and the same
2. When a is -ve, they are not the same
For example;
a = -10, b = 3
Remainder of -10 % 3 = -1
for Modulo, add a greater multiple of 3 to your 'a' and calculate the remainder.
-10 + 12 = 2
2 % 3 = 2 is your answer
The modulo operation is defined as the mathematical modulo operation:
Mathematical operations such as addition, subtraction, negation,
multiplication, division, and the mathematical functions defined later
in this clause should always be understood as computing exact
mathematical results on mathematical real numbers, which do not
include infinities and do not include a negative zero that is
distinguished from positive zero.
Your question:
ToInt32(-1) equals ToInt32(1)
Well, no:
Let posInt be sign(number) * floor(abs(number)).
posInt = sign(-1) * floor(abs(-1)) = -1;
Let int32bit be posInt modulo 232; that is, a finite integer value k
of Number type with positive sign and less than 232 in magnitude such
that the mathematical difference of posInt and k is mathematically an
integer multiple of 232.
int32bit = posInt mod 4294967296 = -1 mod 4294967296 = 4294967295
(wolfram alpha link for mathematical result)
If int32bit is greater than or equal to 231, return int32bit − 232,
otherwise return int32bit.
Because 4294967295 >= 2147483648, we return 4294967295 - 4294967296, I.E. -1.
If we run the same steps for ToInt32(1), we get 1. So they don't have the same result.
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).