What's the best way to perform the following conversions in JavaScript? I have currencies stored as floats that I want rounded and converted to integers.
1501.0099999999999909 -> 150101
12.00000000000001 -> 1200
One way to do this is to use the toFixed method off a Number combined with parseFloat.
Eg,
var number = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(5));
console.log(truncated);
toFixed takes in the number of decimal points it should be truncated to.
To get the output you need, you would only need `toFixed(2)' and multiple the result by 100.
Eg,
var number = 1501.0099999999999909;
var truncated = parseFloat(number.toFixed(2)) * 100;
console.log(truncated);
Related
i have strings that represents money. E.g 29.00 or 29.10 or 29.13 the currency however can change and does not necessarily lead to a value that has two decimal places by default (Yen for example does not have decimal places at all)
Now, i use Decimal.js to execute calculations with these values
For example i am multiplying with a percentage
let d = new decimal("29.00")
let e = d.mul(0.133333333333).toDP(d.decimalPlaces())
The result of this however is rounded to 0 decimal places as the constructer strips away the trailing zeros and sets decimalPlaces to 0.
How can i get a decimal value that always has to amount of decimal places provided by the input string? In this example d.decimalPlaces should return 2 (because 29.00 has to decimal places).
Alternative solution: How do i extract the number of decimal places out of the string?
You mean this?
const keepDecimal = (str,mul) => {
const dec = str.split(".");
const numDec = dec.length===2?dec[1].length:0;
return (str*mul).toFixed(numDec);
}
console.log(keepDecimal("29.13",0.133333333333))
console.log(keepDecimal("29",0.133333333333))
I need a rounding down many many decimal places down, basically roundTo but supposedly rounding down at the spot. Example,
take the number, 1.087179939485353505
but to the fifth place, with roundTo of 6
roundTo(1.087179939485353505, 6) is 1.08718
I need 1.08717 not 1.08718 in javascript.
var Variable = roundTo(Variable / 1000000000000000000, 6);
Resolved
There seems to be no native javascript decimal rounding function that rounds down. One of two options are available.
Convert to string and manipulate the data that way (makes the most sense).
Utilize a number and multiply, floor then re-divide again for your number
How about convert to string, slice and convert back to number.
const roundTo = num => Number(String(num).slice(0, 7));
console.log(roundTo(1.087179939485353505));
You could use regex to get 5 decimals
function roundTo(number) {
var result= number.toString().match(/^\d+(\.\d{0,5})/)[0];
console.log(result);
}
roundTo(1.087179939485353505);
var Variable = Variable / 1000000000000000000;
Variable *= 1000000;
Variable = Math.floor(Variable);
Variable /= 1000000;
var Variable = roundTo(Variable, 6);
I took my decimal, multiplied it by how many places I wanted to roundTo, math floor for absolute low rounding and divided it once again before lastly using roundTo for the precise decimal place. Seems the only way.
How can i convert a number, a input from my test case which will be of either integer or float, into a float/string number of always with 8 decimal places? say for example, if my input is 3, then i should convert into '3.00000000', if my input is 53.678, then i should convert into '53.67800000'. I have googled and tried with few conversion types like parsing, toPrecision() but could not convert it. Any help is much appreciated.
expect(a).to.equal(b) // a and be should be of same number with types too
expect(a).to.equal(b)
In JavaScript, Number is a double-precision float.
Its precision cannot be expressed in decimal places, it varies depending on how big the number is. Above Number.MAX_SAFE_INTEGER, for example, the precision is "less than 0 decimal places":
const large = 9007199254740992;
const larger = large + 1;
console.log(large === larger);
To convert a Number to a String with a fixed number of decimal places, use .toFixed(), as #epascarello suggested:
const input = 3;
const str = input.toFixed(8);
console.log(str);
As for doing financial calculations, some say you should never use IEEE 754 floats (such as JavaScript's Numbers), although many of the largest companies in finance do just that.
To be on the safe side, use a bignum library such as big.js.
I'm new to writing JavaScript, I'm trying to convert two values from a string to a number, however, I have tried to doing the following approaches but none seem to work.
Example:
const num = parseInt('100.00') // returns 100
const num = Number('100.00') // returns 100
const num = +'100.00'; // returns 100
I need to return 100.00 as a number I have gone to other similar post they didn't seem to help, all knowledge is appreciated thanks!
In Javascript everything is Number, which is double-precision floating point 64 bit number (=decimal).
100.00 is equal to 100, therefore it shows you 100.
What you are asking is not possible, the decimal 100 is not representable as 100.00 as number, you can only represent it as a String with help of toFixed;
var num = 100;
var strNum = num.toFixed(2); // in this case you have a string instead of a number
console.log(typeof num, num);
console.log(typeof strNum, strNum);
It seems to me that all the approaches you have tried work.
Internally, JavaScript stores all numbers using the floating point format. It uses the minimum number of decimals needed when it displays the value.
This is 0 for integer numbers as 100. 100.00 is still 100, adding any number of 0 after the decimal point doesn't change its value.
The recommended method to parse a string that looks like a number is to use Number.parseInt() or Number.parseFloat().
parseFloat() recognizes only numbers written in base 10 but parseInt() attempts to detect the base by analyzing the first characters of the input string. It automatically recognizes numbers written in bases 2, 8, 10 and 16 using the rules described in the documentation page about numbers. This is why it's recommended to always pass the second argument to parseInt() to avoid any ambiguity.
Regarding your concern, use Number.toFixed() to force its representation using a certain number of decimal digits, even when the trailing digits are 0:
const num = parseInt('100.00');
console.log(num); // prints '100'
console.log(num.toFixed(2)); // prints '100.00'
I'm performing the following operation in Javascript:
0.0030 / 0.031
How can I round the result to an arbitrary number of places? What's the maximum number that a var will hold?
Modern browsers should support a method called toFixed(). Here's an example taken from the web:
// Example: toFixed(2) when the number has no decimal places
// It will add trailing zeros
var num = 10;
var result = num.toFixed(2); // result will equal 10.00
// Example: toFixed(3) when the number has decimal places
// It will round to the thousandths place
num = 930.9805;
result = num.toFixed(3); // result will equal 930.981
toPrecision() might also be useful for you, there is another excellent example on that page.
For older browsers, you can achieve it manually using Math.round. Math.round() will round to the nearest integer. In order to achieve decimal precision, you need to manipulate your numbers a bit:
Multiply the original number by 10^x
(10 to the power of x), where x is
the number of decimal places you
want.
Apply Math.round()
Divide by 10^x
So to round 5.11111111 to three decimal places, you would do this:
var result=Math.round(5.111111*1000)/1000 //returns 5.111
The largest positive finite value of the number type is approximately 1.7976931348623157 * 10308. ECMAScript-262 3rd ed. also defines Number.MAX_VALUE which holds that value.
To answer Jag's questions:
Use the toFixed() method. Beware; it returns a string, not a number.
Fifteen, maybe sixteen. If you try to get more, the extra digits will be either zeros or garbage. Try formatting something like 1/3 to see what I mean.