Do not strip trailing zeros in JavaScript Decimal constructor - javascript

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))

Related

Round Down Decimal Places Javascript

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 to convert a number to float with 8 point decimal places in javascript

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.

parsing string to decimal doesn't return decimals JavaScript

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'

Converting floating point numbers to integers, rounding to 2 decimals in JavaScript

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);

I need to round the number of a field

I have tried many things about the rounding of a filed but I get NaN, here is what I am trying to round up to 999999,9
document.forms[0].NB_CONCN_MOY_DCO_MS
I have tried Math.round(document.forms[0].NB_CONCN_MOY_DCO_MS.value)
and
document.forms[0].Math.round(NB_CONCN_MOY_DCO_MS.value)
what can I do now.
If you want to round a number to one decimal place in JavaScript, use someNumber.toFixed(1). Note that the value of form fields is a string (not a number) so you'll want to convert it to a number first.
var n = document.forms[0].NB_CONCN_MOY_DCO_MS.value * 1;
var rounded = n.toFixed(1);
If your value has commas in it to represent decimal values, you will need to fix the string to use periods instead first:
var n = document.forms[0].NB_CONCN_MOY_DCO_MS.value.replace(/,/,',') * 1;
var rounded = n.toFixed(1);

Categories