Javascript - Format number to always show the original decimal places - javascript

I need a js function that show the original count of decimals in a number. For example:
value display
2.31 2
1.0 1
2.3500 4
The problem is that i dont know how get the count of decimals.
I have that code:
value=2.3500;
return CountofDecimals(value); // must be display 4:
Anything help??? Thanks :P

That's not possible. There's no difference between the number 3.5 and 3.50 in JavaScript, or indeed in any other common programming language.
If you actually mean they're strings (value = '2.3500' rather than value = 2.3500) then you can use indexOf:
var decimalPlaces = value.length - value.indexOf('.') - 1;

Caveat: I hate this answer, I don't really advocate it
Don't store it as a number, store it as a string. This can result in "stringly typed" code quickly so it is inadvisable. It is a workaround since JavaScript uses a float as the number type.
Alternatively store it as an Object and parse out the format via a function call:
{ value = "1.2345", decimal = 4}
and use that to create the correct number format. If I had the requirement this is probably the hack I'd use. Or, I would have my server return the formatted string as you can pull that off easily server side.

If it would be possible take these numbers as strings, it definitely is possible..And quite simple actually.
function countDecimals(string){
var delimiters = [",","."];
for(var i = 0; i<delimiters.length; i++){
if(string.indexOf(delimiters[i])==-1) continue;
else{
return string.substring(string.indexOf(delimiters[i])+1).length;
}
}
}

You could use this function:
function decimalplaces(number)
{
numberastring = number.toString(10);
decimalpoint = numberastring.indexOf(".");
if(decimalpoint == -1)
{
return 0;
}
else
{
return numberastring.length - decimalpoint - 1;
}
}

Related

How to use .toFixed() (or any alternative) on Nerdamer.solve solutions?

I'm using Nerdamer.solve() to get some linear equation roots. It's working fine but I wonder if there is any way to get only the first 4 decimals of every solution.
EquationSolver.js
//First step, using Nerdamer to solve the equation stored in value
sol_raw = this.nerdamer.solve(value,'x');
xs = this.nerdamer(sol_raw.toString());
//Second step, using Function() in order to evaluate the solutions
solution= Function('return ' + this.nerdamer(xs).evaluate().toString())()
At this point, I'm getting correct results like: 1.74343434. Since I'm rendering the results using Katex, I would like to know where to implement .toFixed(4) or any pseudo way (maybe a Nerdamer method to use n number of decimals on .evaluate()?).
Note.
The result (solution) is a string like [1.74343434, 0.434343, ...] so I could transform it into a float variable and then use .toFixed() but this not an easy solution because the number of roots depends on the equation's grade.
Nerdamer's documentation about evaluate: documentation
#CoronelV,
Another possible approach is to create a toFixed function for formatting the numbers which would take into account real and complex solutions and then calling it on your solutions. Here's a more generalized approach.
var toFixed = function(value, n) {
var img = Number(nerdamer.imagpart(value).text()).toFixed(n);
var real = Number(nerdamer.realpart(value).text()).toFixed(n);
// Format the number assuming i denotes imaginary in your case
var formatted = '';
if(real !== '0.0000') {
formatted += real;
}
if(img !== '0.0000') {
// Put the plus sign betweent the real and imaginary
if(img.charAt(0) !== '-' && formatted) {
formatted += '+';
}
// Assuming you're using i and not j for instance
formatted += img+'i';
}
return formatted;
};
So in your case this would be become something like:
sol_raw = this.nerdamer.solve(value,'x');
xs = this.nerdamer(sol_raw.toString()).each(function(solution) {
roundedSolutions.push(toFixed(solution, 4));
});
this.setState({
solution: roundedSolution.join(''),
equation:value})
This would possibly eliminate the need for your try catch block.
Since the solution is rendered using KaTeX, it's possible rounding the solution via Latex's package, but its even simplest taking the suggestion of #Dj Burb.
Here is my approach:
try {
sol_raw = this.nerdamer.solve(value,'x');
xs = this.nerdamer(sol_raw.toString());
Function('return '+ this.nerdamer(xs).evaluate().toString())().forEach(element => {
roundedSolution.push(element.toFixed(4)) });
} catch (e) {
}
this.setState({
solution: roundedSolution.join(''),
equation:value})
The use of try catch is imperative because while writing the equation, solution.toFixed() returns an error.

How to transform a binary integer into it's partial by shifting it all right of the "."

Let's say we have a binary integer, which I'll call "A", like 101110101100100011. I want an efficient javascript function that makes the whole value partial (like the digits after a "."). So our function, which I'll call intToPart should return 0.101110101100100011 if we input "A".
My 1st idea is to do:
var A=191267 //our binary number in decimal. The computer will read it as "101110101100100011" when doing math.
function intToPart(myInt){
var myNum=myInt.toString(2).length;
return myInt/(1<<myNum);
}
Is their a much more efficient way of doing this, or is my way the best? My function returns the correct value, but I am not sure if there is some special way to bit shift it that is better.
It should be more efficient because there's no call to toString.
var A = 191267 //our binary number in decimal. The computer will read it as "101110101100100011" when doing math.
function intToPart(myInt) {
var myNum = 0, r = myInt;
while (r!==0) { r >>= 1; myNum++ }
return myInt / (1 << myNum);
}
console.log(intToPart(A))
or
var A = 191267 //our binary number in decimal. The computer will read it as "101110101100100011" when doing math.
function intToPart(myInt) {
return myInt/(2**Math.ceil(Math.log2(myInt)));
}
console.log(intToPart(A))

Number converted in 1e+30

How to convert 1e+30 to 1000000000000000000000000000000
I want number as it is entered by User do not convert like 1e+30.
How can achieve this? Is there any way to display actual digits after parse it to float or int?
The core library doesn't give you any support for numbers that don't fit into the native number type, so you'll probably want to use a third party library to help you with large decimals.
For example, https://mikemcl.github.io/decimal.js/
new Decimal('1e+30').toFixed()
// "1000000000000000000000000000000"
You may use toLocaleString
(1000000000000000000000000000000).toLocaleString("en-US", { useGrouping: false })
You can make use of new Array() and String.replace, but it will only be in the form of String
function toNum(n) {
var nStr = (n + "");
if(nStr.indexOf(".") > -1)
nStr = nStr.replace(".","").replace(/\d+$/, function(m){ return --m; });
return nStr.replace(/(\d+)e\+?(\d+)/, function(m, g1, g2){
return g1 + new Array(+g2).join("0") + "0";
})
}
console.log(toNum(1e+30)); // "1000000000000000000000000000000"
Now it's more robust as it doesn't fail even if a really huge number such as 12e100 which will be converted to 1.2e+101, is provided as the . is removed and the last set of digits decremented once. But still 100% accuracy can't be ensured but that is because of limitations of floatation maths in javascript.

String Conversion in Javascript (Decimal to Binary)

A newbie here! Wondering why the following conversion fails!
var num = prompt("Enter num");
alert(num.toString(2));
If num input is 32. I get 32 as num alert message too.
try
(+num).toString(2)
,
Number(num).toString(2)
or
parseInt(num, 10).toString(2)
Any of those should work better for you.
The issue is that the toString method of javascript Number objects overrides the toString method of Object objects to accept an optional radix as an argument to provide the functionality you are looking for. The String object does not override Object's toString method, so any arguments passed in are ignored.
For more detailed information about these objects, see the docs at Mozilla:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String#Methods
or W3 schools:
http://www.w3schools.com/jsref/jsref_tostring_number.asp
http://www.w3schools.com/jsref/jsref_obj_string.asp
With this function you can specify length of the output.
For example decbin(7,4) produces 0111.
function decbin(dec,length){
var out = "";
while(length--)
out += (dec >> length ) & 1;
return out;
}
demo
Here is my solution that does not use parseInt, but rather a method that shows the logic behind the conversion of decimal to binary.
This method prints the bits to the array which you may later print out if you wish:
var number = 156;
var converted = [];
while(number>=1) {
converted.unshift(number%2);
number = Math.floor(number/2);
}
The converted array will now appear like so:
[1,0,0,1,1,1,0,0]
which of course converts back to 156.
/**
Convert a decimal number to binary
**/
var toBinary = function(decNum){
return parseInt(decNum,10).toString(2);
}
/**
Convert a binary number to decimal
**/
var toDecimal = function(binary) {
return parseInt(binary,2).toString(10);
}
Finally use it
var num= prompt("Enter num");
alert(toBinary(num));
Cast it to an integer first. At the moment you're converting a string to it's binary representation.
num = +num;

javascript parseFloat '500,000' returns 500 when I need 500000

How would it be a nice way of handling this?
I already thought on removing the comma and then parsing to float.
Do you know a better/cleaner way?
Thanks
parseFloat( theString.replace(/,/g,'') );
I don't know why no one has suggested this expression-
parseFloat( theString.replace(/[^\d\.]/g,'') );
Removes any non-numeric characters except for periods. You don't need custom functions/loops for this either, that's just overkill.
Nope. Remove the comma.
You can use the string replace method, but not in a one liner as a regexp allows.
while(str.indexOf(',')!=-1)str= str.replace(',','');
parseFloat(str);
Or to make a single expression without a regexp=
return parseFloat(str.split(',').join(''));
I'd use the regexp.
I don't have enough reputation to add a comment, but for anyone wondering on the performance for regex vs split/join, here's a quick fiddle: https://jsfiddle.net/uh3mmgru/
var test = "1,123,214.19";
var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
var a = parseFloat(test.replace(/,/g,''));
}
var t1 = performance.now();
document.write('Regex took: ' + (t1 - t0) + ' ms');
document.write('<br>')
var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
var b = parseFloat(test.split(',').join(''));
}
var t1 = performance.now();
document.write('Split/join took: ' + (t1 - t0) + ' ms');
The results I get are (for 1 million loops each):
Regex: 263.335 ms
Split/join: 1035.875 ms
So I think its safe to say that regex is the way to go in this scenario
Building on the idea from #kennebec, if you want to make sure that the commas are correct, and you don't want to replace commas, you could try something like this:
function myParse(num) {
var n2 = num.split(",")
out = 0
for(var i = 0; i < n2.length; i++) {
out *= 1000;
out += parseFloat(n2[i])
}
return out
}
alert(myParse("1,432,85"));
// Returns 1432085, as the comma is misplaced.
It may not be as fast, but you wanted alternatives :)
What about a simple function to solve most of the common problems?
function getValue(obj) {
Value = parseFloat( $(obj).val().replace(/,/g,'') ).toFixed(2);
return +Value;
}
The above function gets values from fields (using jQuery) assuming the entered values are numeric (I rather validate fields while user is entering data, so I know for sure field content is numeric).
In case of floating point values, if well formatted in the field, the function will return a float point value correctly.
This function is far from complete, but it quickly fix the "," (comma) issue for values entered as 1,234.56 or 1,234,567. It will return valid number as far the content is numeric.
The + (plus) sign in front of the variable Value in the return command is a "dirty trick" used in JavaScript to assure the variable content returned will be numeric.
it is easy to modify the function to other purposes, such as (for instance), convert strings to numeric values taking care of the "," (comma) issue:
function parseValue(str) {
Value = parseFloat( str.replace(/,/g,'') ).toFixed(2);
return +Value;
}
Both operations can even be combined in one function. I.e.:
function parseNumber(item,isField=false) {
Value = (isField) ? parseFloat( $(item).val().replace(/,/g,'') ).toFixed(2) : parseFloat( item.replace(/,/g,'') ).toFixed(2)
return +Value;
}
In such case, if function is called result = parseNumber('12,092.98'); it will parse the value as it is a String. But if called as result = parseNumber('#MyField', true); it will try to obtain the value from '#MyField'.
As I said before, such functions are far from complete, and can be expanded in many ways. One idea is to check the first character of the given parameter (string) and decide based on the string format where to obtain the value to be parsed (if 1st character is = '#' then it is an ID from a DOM object, otherwise, if it begins with a number, it must be a string to be parsed).
Try it... Happy coding.

Categories

Resources