Say:
var x = 6.450000000000003;
var y = 5.234500000000002;
These are the results of floating point division, so the 3 and the 2 need to be removed. How can I trim x to 6.45 and y to 5.2345 given that they have different levels of precision?
You could use Number#toFixed and convert the string back to number.
var x = 6.450000000000003,
y = 5.234500000000002;
x = +x.toFixed(5);
y = +y.toFixed(5);
console.log(x);
console.log(y);
You could use Math.round but you must choose a precision.
(Otherwise, you are losing percision and you don't want that!)
var x = 6.450000000000003;
var y = 5.234500000000002;
console.log(Math.round(x * 1000000) / 1000000);
console.log(Math.round(y * 1000000) / 1000000);
Try this function. If, as you say, you're simply looking to remove the end digit and remove trailing zeros, the following code could help.
function stripZeroes(x){
// remove the last digit, that you know isn't relevant to what
// you are working on
x = x.toString().substring(0,x.toString().length-1);
// parse the (now) String back to a float. This has the added
// effect of removing trailing zeroes.
return parseFloat(x);}
// set up vars for testing the above function
var x = 6.450000000000003;
var y = 5.234500000000002;
// test function and show output
console.log(stripZeroes(x));
console.log(stripZeroes(y));
Related
Ok, I'm not a coder, I've no school about it but ... I can't figure out why this little operation returns a NaN value!
I've this var at the beginning
// Varialbes for simulation purpose
var Simulation = false;
var FakeCapital = 0;
var PercentOfTotal = 100;
// Variables
var Capital = (engine.getBalance() / 100).toFixed(2);
var UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
var StartingBalance = UsableBalance;
if (FakeCapital > 0 && Simulation) {
Capital = FakeCapital;
UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
StartingBalance = UsableBalance;
}
So If I activate the similation var and if I want to use another capital, the script use the fakecapital to test my script.
Here all works but I think that here there's the problem, specially the UsableBalance = Math.floor(PercentOfTotal / 100 * Capital);
Because when the script run:
If I don't use the simulation, all goes right
If I use the simulation and the fake capital, all goes right
But if I use the simulation and I want to use the real capital, the UsableBalance var is strange, not immediately but when the script runs! I try to explain better
Let's assume that I use the simulation phase and I want to use the real capital
Your ballance is: 87.26 bits.
I'll use: 87 bits for this session, as your request.
Here all ok, but this code:
if (TemporaryLoss <= 0) {
Capital += LastProfit;
UsableBalance = Math.floor((PercentOfTotal / 100) * Capital);
TemporaryLoss = 0;
}
Return this:
TemporaryLoss: 0
Capital: 87.26
LastProfit: 1.0299999999999998
PercentOfTotal: 100
Capital: 87.261.0299999999999998
Why the math return this strange number? like a concatenation of 2 numbers? Seems that the script use the var like a text and not like a numbers.
Any Idea?
You make a string with toFixed()
var Capital = (engine.getBalance() / 100).toFixed(2);
and used it later as number, but it is a string.
Capital += LastProfit;
Solution: If fixed is necessary, then use parseFloat() to make a number again.
Lets take an example :
var x = 1;
var y = '1';
var z = x + (y*10)
the datatype of variable y is implicitly coerced to number for the current operation, to evaluate the value of z.
So, for z , y is taken as a number because (y*10) caused implicit coercion, but doesn't change y itself to number
In your case ,
var Capital = (engine.getBalance() / 100).toFixed(2);
causes Capital to become a string.
Hence any further addition operations with Capital result in concatenation
You will have to explicitly convert to int or float as mentioned earlier.
input : -81.82637799999999(14 numbers after decimal point)
output :-81.8263779999999(13 numbers after decimal point)
How can I implement this using javascript?
Well try this.
See if it works for you
var x = -81.82637799999999;
x = x.toString(); // convert to string
alert(x.length);
x = x.substring(0, x.length - 1); // cut out last character
alert(x.length);
x = parseFloat(x); // convert it back to float
https://jsfiddle.net/9sngtp3n/1/
OK, I'm a novice at this but keen so help appreciated.
I have the following script that looks at field q13 which is a value and may or may not contain two decimal places. I then use the value returned and multiply by .8 to give 80% which I want to display in field q14. This works fine but decimal places can 1, 2, 3 etc. How do I ensure that I always return 2 decimal places? Rounding is not absolutely necessary.
function parseNumber(n) // Define a new function
{
var f = parseFloat(n); // Convert to float number.
return isNaN(f) ? 0 : f; // Treat invalid input as 0;
}
$("#Field13").on("change",function() {
var x = parseNumber($("#q13 input").val());
var y = x * 0.8;
$("#q14 input").val(y);
});
Use toFixed() to specify number of digits to appear after the decimal point
$("#q14 input").val(y.toFixed(2));
use toFixed passing a number of decimals you want to have:
function parseNumber(n) // Define a new function
{
var f = parseFloat(n); // Convert to float number.
return isNaN(f) ? 0 : f; // Treat invalid input as 0;
}
$("#Field13").on("change",function() {
var x = parseNumber($("#q13 input").val());
var y = x * 0.8;
$("#q14 input").val(y.toFixed(2));
});
This question already has answers here:
Truncate (not round off) decimal numbers in javascript
(32 answers)
Closed 8 years ago.
Im trying to get a number with precision to 2 decimals, for example this is what I want, if I have the numbers:
3.456 it must returns me 3.45
3.467 = 3.46
3.435 = 3.43
3.422 = 3.42
I don't want to round up or down or whatever just to get the numbers I see 2 places after .
Thanks
Okay, here is the answer
var a = 5.469923;
var truncated = Math.floor(a * 100) / 100; // = 5.46
Thanks everyone for helping.
Assuming Positive Numbers:
The code:
function roundDown(num,dec) {
return Math.floor(num*Math.pow(10,dec))/Math.pow(10,dec);
}
The test:
function test(num, expected) {
var val = roundDown(num,2);
var pass = val === expected;
var result = pass ? "PASS" : "FAIL";
var color = pass ? "GREEN" : "RED";
console.log("%c" + result + " : " + num + " : " + val, "background-color:" + color);
}
test(3.456, 3.45);
test(3.467, 3.46);
test(3.435, 3.43);
test(3.422, 3.42);
Basic idea:
Take number
Multiply the number to move decimal place to number of significant figures you want
Floor the number to remove the trailing numbers
Divide number back to get the correct value
If you want to have a trailing zero, you need to use toFixed(2) which will turn the number to a string.
function roundDown(num,dec) {
return Math.floor(num*Math.pow(10,dec))/Math.pow(10,dec).toFixed(2);
}
and the test cases would need to change to
test(3.456, "3.45");
test(3.467, "3.46");
test(3.435, "3.43");
test(3.422, "3.42");
Another option is a regular expression.
function roundDown(num,dec) {
var x = num.toString().match(/(\d*(\.\d{2}))?/);
return x ? parseFloat(x[0]) : "";
//return x ? parseFloat(x[0]).toFixed(2) : "";
}
Use String operation to achieve it.
var n = 4.56789;
var numbers = n.toString().split('.');
result = Number(numbers[0]+"."+numbers[1].substr(0,2));
alert(result);
Fiddle
You are looking at the number as if it were a string of digits, rather than a single value, so treat it like a string.-
function cutoff(n, cut){
var parts= String(n).split('.'), dec= parts[1];
if(!cut) return parts[0];
if(dec && dec.length>cut) parts[1]= dec.substring(0, cut);
return parts.join('.');
}
var n= 36.938;
cutoff(n,2)
/* returned value: (String)
36.93
*/
If you want a number, +cutoff(n,2) will do.
function truncateDec(num, decplaces) {
return (num*Math.pow(10,decplaces) - num*Math.pow(10,decplaces) % 1)/Math.pow(10,decplaces);
}
alert(truncateDec(105.678, 2)); // Returns 105.67
alert(truncateDec(105.678, 1)); // Returns 105.6
This could be simplified further if you do not require a dynamic number of decimal places
function truncateDec(num) {
return (num*100 - num*100 % 1)/100;
}
alert(truncateDec(105.678)); // Returns 105.67
How does it work?
The concept is that the main truncation works by getting the remainder from dividing the original decimal by 1. The remainder will be whatever is in the decimals places. The remainder operator is %
105.678 % 1 = 0.678
By subtracting this remainder from the original number, we will be left with only the integer.
105.678 - 0.678 = 105
To include x number of decimal places, we need to first multiply the original number by 10 to the power of that number of decimal places, thereby shifting the decimal backward by x positions. In this example, we will take x = 2.
105.678 * 10^2
= 105.678 * 100
= 10567.8
Now, we repeat the same procedure by subtracting the remainder again.
10567.8 % 1 = 0.8
10567.8 - 0.8 = 10567
And to return back to the number of places as requested, we divide it back by 10^x
10567 / 10^2
= 10567 / 100
= 105.67
Hope it helps!
Is there a math function in JavaScript that converts numbers to positive value?
You could use this...
Math.abs(x)
Math​.abs() | MDN
What about x *= -1? I like its simplicity.
I know this is a bit late, but for people struggling with this, you can use the following functions:
Turn any number positive
let x = 54;
let y = -54;
let resultx = Math.abs(x); // 54
let resulty = Math.abs(y); // 54
Turn any number negative
let x = 54;
let y = -54;
let resultx = -Math.abs(x); // -54
let resulty = -Math.abs(y); // -54
Invert any number
let x = 54;
let y = -54;
let resultx = -(x); // -54
let resulty = -(y); // 54
Math.abs(x) or if you are certain the value is negative before the conversion just prepend a regular minus sign: x = -x.
The minus sign (-) can convert positive numbers to negative numbers and negative numbers to positive numbers. x=-y is visual sugar for x=(y*-1).
var y = -100;
var x =- y;
unsigned_value = Math.abs(signed_value);
var posNum = (num < 0) ? num * -1 : num; // if num is negative multiple by negative one ...
I find this solution easy to understand.
If you'd like to write interesting code that nobody else can ever update, try this:
~--x
Multiplying by (-1) is the fastest way to convert negative number to positive. But you have to be careful not to convert my mistake a positive number to negative! So additional check is needed...
Then Math.abs, Math.floor and parseInt is the slowest.
https://jsperf.com/test-parseint-and-math-floor-and-mathabs/1
Negative to positive
var X = -10 ;
var number = Math.abs(X); //result 10
Positive to negative
var X = 10 ;
var number = (X)*(-1); //result -10
I did something like this myself.
num<0?num*=-1:'';
It checks if the number is negative and if it is, multiply with -1
This does return a value, its up to you if you capture it. In case you want to assign it to something, you should probably do something like:
var out = num<0?num*=-1:num; //I think someone already mentioned this variant.
But it really depends what your goal is. For me it was simple, make it positive if negative, else do nothing. Hence the '' in the code.
In this case i used tertiary operator cause I wanted to, it could very well be:
if(num<0)num*=-1;
I saw the bitwise solution here and wanted to comment on that one too.
~--num; //Drawback for this is that num original value will be reduced by 1
This soultion is very fancy in my opinion, we could rewrite it like this:
~(num = num-1);
In simple terms, we take the negative number, take one away from it and then bitwise invert it. If we had bitwise inverted it normally we would get a value 1 too small.
You can also do this:
~num+1; //Wont change the actual num value, merely returns the new value
That will do the same but will invert first and then add 1 to the positive number.
Although you CANT do this:
~num++; //Wont display the right value.
That will not work cause of precedence, postfix operators such as num++ would be evaluated before ~ and the reason prefix ++num wouldnt work even though it is on the same precedence as bitwise NOT(~), is cause it is evaluated from right to left. I did try to swap them around but it seems that prefix is a little finicky compared to bitwise NOT.
The +1 will work because '+' has a higher precedence and will be evaluated later.
I found that solution to be rather fun and decided to expand on it as it was just thrown in there and post people looking at it were probably ignoring it. Although yes, it wont work with floats.
My hopes are that this post hasn't moved away from the original question. :/
My minimal approach
For converting negative number to positive & vice-versa
var num = -24;
num -= num*2;
console.log(num)
// result = 24
If you want the number to always be positive no matter what you can do this.
function toPositive(n){
if(n < 0){
n = n * -1;
}
return n;
}
var a = toPositive(2); // 2
var b = toPositive(-2); // 2
You could also try this, but i don't recommended it:
function makePositive(n){
return Number((n*-n).toString().replace('-',''));
}
var a = makePositive(2); // 2
var b = makePositive(-2); // 2
The problem with this is that you could be changing the number to negative, then converting to string and removing the - from the string, then converting back to int. Which I would guess would take more processing then just using the other function.
I have tested this in php and the first function is faster, but sometimes JS does some crazy things, so I can't say for sure.
You can use ~ operator that logically converts the number to negative and adds 1 to the negative:
var x = 3;
x = (~x + 1);
console.log(x)
// result = -3
I know another way to do it. This technique works negative to positive & Vice Versa
var x = -24;
var result = x * -1;
Vice Versa:
var x = 58;
var result = x * -1;
LIVE CODE:
// NEGATIVE TO POSITIVE: ******************************************
var x = -24;
var result = x * -1;
console.log(result);
// VICE VERSA: ****************************************************
var x = 58;
var result = x * -1;
console.log(result);
// FLOATING POINTS: ***********************************************
var x = 42.8;
var result = x * -1;
console.log(result);
// FLOATING POINTS VICE VERSA: ************************************
var x = -76.8;
var result = x * -1;
console.log(result);
For a functional programming Ramda has a nice method for this. The same method works going from positive to negative and vice versa.
https://ramdajs.com/docs/#negate