toFixed function on large numbers - javascript

I have following number with e+ on it
9.074701047887939e+304
I want to take only 9.07
So I tried below , but its not working , its returning full output
console.log(parseFloat(9.074701047887939e+304).toFixed(2));
Ps : I also need the code to work for normal numbers aswell for example 892.0747010 , should output 892.07

toFixed trims digits after the decimal point, but your actual number is very large - it doesn't have a decimal point.
If you don't know in advance whether the number is large or not, one option is to call toFixed(2) on the number first (trimming off and properly rounding digits past the decimal point for small numbers), then using a regular expression to take the numeric part only (removing the e if it exists), then call toFixed(2) again (trimming off and properly rounding digits past the decimal point for large numbers):
const fix = num => Number(
num.toFixed(2).match(/\d+(?:\.\d+)?/)[0]
).toFixed(2);
console.log(fix(9.074701047887939e+304));
console.log(fix(123.4567));
console.log(fix(12345));

Since you mentioned for both 9.074701047887939e+304 and 9.074701047887939, you want the answer to be 9.07.
For 9.074701047887939e-304 I assume you want 9.07 too, although you might actually want 0.00.
const twoDecimal = (a =>
(a.toString().match(/e/) ? Number(a.toString().match(/[^e]*/)[0]) : a).toFixed(2)
);
console.log(twoDecimal(9.074701047887939e+304));
console.log(twoDecimal(9.074701047887939e-304));
console.log(twoDecimal(9.074701047887939));
console.log(twoDecimal(789.074701047887939));
console.log(twoDecimal(0.00001));
console.log(twoDecimal(0.20001));
console.log(twoDecimal(-9.074701047887939e+304));
console.log(twoDecimal(-9.074701047887939e-304));
console.log(twoDecimal(-9.074701047887939));
console.log(twoDecimal(-789.074701047887939));
console.log(twoDecimal(-0.00001));
console.log(twoDecimal(-0.20001));
console.log(twoDecimal(0));

Related

Add trailing zeros to match precision dynamically

I am creating a react crypto project and just trying to figure out how to add trailing zeros dynamically without using the toFixed method. The reason why I am avoiding that toFixed method is because though it gets the precision right and tacks on desired trailing zeros, it rounds the number. Which can be misleading. So I am on the last part of getting this thing to operate correctly.
const getInternalAssetBalance = (selectedAsset, pairType, useFreeTotal = false) => {
const exchangeInternalAccount = holdingsByAccount.find(account => account.exchange === 'REGULAR');
const assetObj = exchangeInternalAccount && exchangeInternalAccount.assets.find(item => item.name === selectedAsset);
};
I have it where it limits the digits after the decimal based on precision(meaning it won't go over the precision specified), however, if a number happens to have less decimal places than the desired precision, it won't tack on the extra trailing zeros. For example lets say we have a number 12.353. If the precision was 5, I would want the result to be 12.35300. So that it tacks on the extra two zeros.
Anyone happen to know how I can dynamically tack on zeros if the balance amount happens to have fewer decimal places than the desired precision so that it matches?
A few remarks:
Since your function returns a number data type, you lose any format that wants to have trailing zeroes in the decimal part. A number value does not have any formatting that goes with it. Just like the native .toFixed method, you need to return a string.
You can still make use of the .toFixed method if you first make the truncation that is needed. This you can do by multiplying the number with a power of 10, truncate it to integer, and then divide it again.
function toFixed(n, precision) {
const coeff = 10**precision;
return (Math.floor(n * coeff) / coeff).toFixed(precision);
}
console.log(toFixed(1.234567, 4)); // 1.2345
console.log(toFixed(1.23, 4)); // 1.2300

Regex to make nondecimal number decimal (add .00)

I have an user input where user can edit price of something. To leave data consistance I would like to manipulate with that string on front-end site.
What I want to do is:
1234 to 1234.00
12.3 to 12.30
12,3 to 12.30
1234.45 to 1234.45
So basicly,
Replace comma with dots
this should be done easy with somehing like:
str.replace(',', '.');
Add dots if number if not decimal and also always change number of digits on two(so add 0 if needed)
I try to do something like:
priceByUser = priceByUser.replace(/^\d*\.?\d*$/, "$1\.00");
unfortunately this really doesnt even work as I expected.
Is there a chance someone can help me to solve this issue?
Thanks
You could consider using a regular expression to replace your commas and periods with just decimal points and then parse the values as floats via parseFloat() then finally, use the toFixed(2) function to indicate that you want two decimal places :
// This will clean up your input (consolidating periods and commas), parse the result
// as a floating point number and then format that number to two decimal places
priceByUser = parseFloat(priceByUser.replace(/,/g,'.')).toFixed(2);
If you wanted an extra-level of validation, you could consider stripping out any non-digit or decimal places after this occurs :
// Sanitize
priceByUser = priceByUser.replace(/,/g,'.').replace(/[^\d\.]/g,'');
// Parse and format
priceByUser = Number(priceByUser).toFixed(2);
Example
You can see a working example here and and example of input/output below :

How can I parse a string as an integer and keep decimal places if they are zeros?

I have these strings: "59.50" & "30.00"
What I need to do is convert them to integers but keep the trailing zeros at the end to effectively return:
59.50
30.00
I've tried:
Math.round(59.50 * 1000) / 1000
Math.round(30.00 * 1000) / 1000
but ended up with
59.5
30
I'm assuming I need to use a different method than Math.round as this automatically chops off trailing zeros.
I need to keep these as integers as they need to be multiplied with other integers and keep two decimals points. T thought this would be fairly straight forward but after a lot of searching I can't seem to find a solution to exactly what I need.
Thanks!
Your premise is flawed. If you parse a number, you are converting it to its numerical representation, which by definition doesn't have trailing zeros.
A further flaw is that you seem to think you can multiply two numbers together and keep the same number of decimal places as the original numbers. That barely makes sense.
It sounds like this might be an XY Problem, and what you really want to do is just have two decimal places in your result.
If so, you can use .toFixed() for this:
var num = parseFloat("59.50");
var num2 = parseFloat("12.33");
var num3 = num * num2
console.log(num3.toFixed(2)); // 733.64
Whenever you want to display the value of the variable, use Number.prototype.toFixed(). This function takes one argument: the number of decimal places to keep. It returns a string, so do it right before viewing the value to the user.
console.log((123.4567).toFixed(2)); // logs "123.46" (rounded)
To keep the decimals - multiply the string by 1
example : "33.01" * 1 // equals to 33.01
Seems you are trying to retain the same floating point, so better solution will be some thing like
parseFloat(string).toFixed(string.split('.')[1].length);
If you want numbers with decimal points, you are not talking about integers (which are whole numbers) but floating point numbers.
In Javascript all numbers are represented as floating point numbers.
You don't need the trailing zeros to do calculations. As long as you've got all the significant digits, you're fine.
If you want to output your result with a given number of decimal values, you can use the toFixed method to transform your number into a formatted string:
var num = 1.5
var output = num.toFixed(2) // '1.50'
// the number is rounded
num = 1.234
output = num.toFixed(2) // '1.23'
num = 1.567
output = num.toFixed(2) // '1.57'
Here's a more detailed description of toFixed: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Why does someNum - Math.floor(someNum) give me different decimal numbers

I have some simple javascript which I want to use to determine if a number needs to be rounded.
Example: User enters 1.2346 and the number is rounded to 1.235 and a message should be displayed to the user informing them that the number was rounded.
Rounding the number isn't the issue, but showing the error message to the user is. I need to find the number of digits after the decimal point.
I use the following code to retrieve the decimal places off of a string. I then count the length of the variable to get the decimal places:
var dp = field_value - Math.floor(field_value);
However, When I test this I enter 1.23 for the value of field_value. When I check the value of field value it is indeed 1.23. When I check the value of Math.floor(field_value) it is indeed 1. But then I check the value of dp and it turns out to be 0.22999999999999998
Why does this subtraction not work the way it is expected?
Problem is given by the fact that floating numbers have a finite representation, take a look here and you will understand how and why.
If problem with roundings is just for printing that number you could use something like sprintf for JS that allows you to format float output as you nee.
Trying to do anything too exact and specific with the representation of a floating point number is always going to a tricky situation. As other people have pointed out, this is a property of IEEE-754 floating point standard. Besides treating it as a string and trying to analyze the number, you could also just round it deterministically to the format you want, doing something like:
function roundFloat(num, decimalPlaces) {
multiplier = Math.pow(10, decimalPlaces);
return Math.round(num * multiplier) / multiplier;
}

how to mandate a number to display 2 decimal places?

I'm aware that the way to truncate a number to 2 decimal places in toFixed(). However, in case the number has just 1 decimal place, I get an error.
What is the way to mandate a number to display >2 decimal places(numbers after the decimals will be 0 in this case) so that toFixed() will not throw an error?
This should work on any input:
var result = Math.round(original*100)/100;
Generally, I would avoid using toFixed(), as it can behave unexpectedly when given non float input. Also, see here:
How to format a float in javascript?
Trying to format number to 2 decimal places jQuery
I think you are trying to apply toFixed on a string ? You could just parse it into a float before using toFixed on it.
var a = '1.0';
a = parseFloat( a );
a = a.toFixed(2);
console.log( a );

Categories

Resources