Convert string with exponential number to floating - node.js

I'm working on a NodeJs script that handles strings with exponential values.
Something like this:
1.070000000000000e+003
Which is the best way to convert (or parse) this string and obtain a floating value?
Thanks for the help.

You may convert by using parseFloat or Number
If you prefer to parse, maybe the best way is by a regular expression:
/-?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/
as suggested here and convert the single capturing group.

Related

How do I parse a float from a string that might contain left-over characters without doing manual parsing?

How do I parse a float from a string that may contain left-over characters, and figure out where it ends, without doing manual parsing (e.g. parseFloat() in JS)?
An example would be the string "2e-1!". I want to evaluate the next float from the string such that I can split this string into "2e-1" and "!" (for example, if I wanted to implement a calculator.) How would I do this without writing a parser to see where the float ends, taking that as an &str, and then using .parse()?
I am aware that this means that I may have to parse nonstandard things such as "3e+1+e3" to 3e+1 (30) and "+e3". This is intended; I do not know all of the ways to format floating point numbers, especially the ones valid to Rust's parse::<f64>(), but I want to handle them regardless.
How can I do this, preferably without external libraries?
As mentioned in the comments, you need to either implement your own floating-point parser or use an external library. The parser in the standard library always errors out when it encounters additional junk in the input string – it doesn't even allow leading or trailing whitespace.
A good external crate to use is nom. It comes with an integrated parser for floating-point numbers that meets your requirements. Examples:
use nom::number::complete::double;
let parser = double::<_, ()>;
assert_eq!(parser("2.0 abc"), Ok((" abc", 2.0)));
let result = parser("Nanananananana hey, Jude!").unwrap();
assert_eq!(result.0, "ananananana hey, Jude!");
assert!(result.1.is_nan());
The parser expects the floating-point number at the very beginning of the string. If you want to allow leading whitespace, you can remove it first using trim_start().

Infix to postfix read negative integers as negative

Im doing a calculator for schoolwork and everything works except my scanner, cause when it takes a negative integer it doesnt see it as a negative number it just sees the subtraction sign as a operator and I want it to see it like a part of the operand:
String exp = "8+4*-12-4";
String[] temp = new String[exp.length()];
temp =exp.split("(?<=[-+*/])|(?=[-+*/])");
this makes it correct if its only positive integers.
for example
input: 8+4*12-4
and the
output:[8, 4, 12, *, +, 4, -]
but with a negative number it doesnt get it right!
so thats what I want help with, thanks in advance
LinkedList <String>list= new LinkedList<String>();
just takes each of the characters in the string and adds each to the resulting list. Instead of doing this, you need to write syntax-aware code. If you can insist on white space between all tokens, then you can split on spaces with, for example, String.split. If not, the simplest alternative is to iterate over the characters in the string "by hand" and create the output that way.
While I suppose it is also possible to use String.split with a non-capturing positive lookahead to also split on operators, figuring out regular expressions to that level of mastery is more difficult than solving the problem in code. I can't give an example for the positive lookahead assertion implementation, as I don't want to take the time to run up a development envirionment, write the code, create test cases and debug it - since I don't think this is the approach you should take in any case.

Converting #% to #.## format

Let me start off with, I am new at this, so bear with me.
I am pulling data in from an excel file and I need an expression that can look at one of my rows that has both decimals and percentages in it. I need them to be uniform and just have decimal format. So basically, some of fields have either 5% (shown with the % sign) and others have .05. I need all of my output to have the .05 type. I have been trying to figure this out for hours and am at a loss.
Currently I am using (DT_DECIMAL,6)REPLACE(TRIM([Percentage Off]),"%","") but that seems to just be stripping the percentage sign off and it doesn't convert the number to a percentage. Any help would be kindly appreciated.
The set of links below will likely get you to the answer.
Note that you may need only a CAST, not a REPLACE.
I do not have a system at hand where to test this, but I expect it to be useful (if not providing the explicit answer) for you.
Cast (SSIS Expression).
Syntax:
(type_spec) expression
REPLACE (SSIS Expression).
Syntax:
REPLACE(character_expression,searchstring,replacementstring)
? : (Conditional) (SSIS Expression).
Syntax:
boolean_expression?expression1:expression2
Operators (SSIS Expression).
SSIS Converting Percent to Decimal.

Vectorize string concatenation in matlab

I am doing a project where I would like to vectorize (if possible), these lines of code in Matlab:
for j=1:length(image_feature(i,:))
string1b=strcat(num2str(j),':',num2str(image_feature(i,j)));
write_file1b=[write_file1b string1b ' '];
end
Basically, what I want to get is an output string in the following way:
1:Value1 2:Value2 3:Value3 ....
Note that ValueX is a number so a real example would be an output like this:
1:23.2 2:34.3 3:110.8
Is this possible? I was thinking about doing something like creating another vector with values from 1 to j, and another j-long vector with only ":", and a num2str(image_feature(i,:)), and then hopefully there is a function f (like a vectorized strcat) that if I do:
f(num2str(1:j),colon_vector,num2str(image_feature(i,:)))
will give me the output I mention above.
Im not sure I understood your question but perhaps this might help
val=[23.2 34.3 110.8]
output = [1:length(val); val]
sprintf('%i: %f ',output)
As output I get
1: 23.200000 2: 34.300000 3: 110.800000
You can vectorize all your array operations to create an array or matrix of numbers very efficiently, but by the very nature of strings in MATLAB, you cannot vectorize the creation of your output string. Theoretically, if you have a fixed length string like in C++, you could concurrently write to different memory locations within the string, but that is not something that is supported by MATLAB. Even if it were, it looks like you have variable-length numbers, so even that would be difficult (unless you were to allocate a specific amount of space per number pair, leading to variable-length spaces between number pairs. It doesn't look like you want to do that, since your examples have exactly one space between all number pairs).
If you'd be interested in efficiently creating a vector, the answer provided by twerdster would accomplish that, but even in that code, the sprintf statement is not concurrent. His code does get rid of the for-loop, which improves efficiency, so I prefer his code to yours.

Is there a generic way to do comparison both numeric and string in Perl?

As everyone knows, the numeric's comparison uses different operators to string's.
So Is there a generic way to do comparison both numeric and string in Perl ?
Should I always check the value is numeric or string before doing the comparison?
I am a freshman in Perl. Please help if you have some idea.
Thanks.
In addition to ways already mentioned, when using perl > 5.10.1, smart matching can be used. Specifically look at lines 29 .. 32 in the referenced table. If one operand look like a number, numeric comparison is used, otherwise fallback to string.
Well, usually you know what kind of data a particular variable holds at a particular point in time. Can you explain more what case you are thinking of where you wouldn't?
There are modules tailored to things like complex version numbers that may have multiple string/numeric parts. Sort::Naturally is one.
You should use numeric comparison when you want to compare numbers and string comparison when you want to compare strings. That's really all there is to it. You're probably overthinking it.
If you really need to test for both string and numeric equality, just test for both:
if ( ( $foo eq $bar ) && ( $foo == $bar ) )
When in doubt, use eq. It works for numbers as well. You only need numeric operations when you want to count something.
Perl will convert numbers to strings and vice-versa when needed, however, not all strings can be represented by numbers, so you'll get a warning and a zero value (while we are at it: always use strict; and use warnings; ).

Resources