Convert Number In Strings to Numeric Form

I need some help in converting strings that contain numbers back into numeric form. Apparently, when I sort string formatted number, the arrangement was according to alphanumeric order (eg. 1, 10,11,2,20,21,3,30... ).

4/15/2002 1:14:40 PM
perl.beginners 29388 articles. 4 followers. Follow

4 Replies

Similar Articles

[PageSpeed] 38
Get it on Google Play
Get it on Apple App Store

on Mon, 15 Apr 2002 13:14:40 GMT, Mok T.Y.-R15382 wrote:

> I need some help in converting strings that contain numbers back into
> numeric form. Apparently, when I sort string formatted number, the
> arrangement was according to alphanumeric order (eg. 1,
> 10,11,2,20,21,3,30... ).

Are you using the correct comparison operator? As

    	perldoc -f sort

explains, the default is string-comparison (i.e. 'cmp'). If you want a 
numeric sort, you need the spaceship operator (i.e. '<=>'):

    	#! /usr/local/perl -w
    	use strict;

    	my @strings = ('12', '1', '50', '101', '13', '501');

    	my @sorted_as_strings = sort { $a cmp $b} @strings;
    	my @sorted_as_numbers = sort { $a <=> $b} @strings;

    	print "Original strings : @strings\n";
    	print "Sorted as strings: @sorted_as_strings\n";
    	print "Sorted as numbers: @sorted_as_numbers\n";

4/15/2002 1:26:55 PM
>>>>> "Mok" == Mok T Y <> writes:

    Mok> Hi, I need some help in converting strings that contain numbers
    Mok> back into numeric form. Apparently, when I sort string
    Mok> formatted number, the arrangement was according to alphanumeric
    Mok> order (eg. 1, 10,11,2,20,21,3,30... ).  Thanks, TY

Since Perl doesn't make your declare your variables' type when you
create them, you need to tell it what kind of data you have when you use
the variable.

In this case, you're sorting lexically rather than numerically.  Use a
sort function like:

  @results = sort {$a <=> $b} @array; # an ascending numerical sort.

instead of:

  @results = sort @array; # which is equal to sort {$a cmp $b} @array.

The difference is '<=>' (numerical comparison) against 'cmp' (lexical

Hope this helps.  perldoc -f sort for more information.

- Chris.
$a=""; Chris Ball | chris@void.$a | www.$a | finger: chris@$a
As to luck, there's the old miners' proverb: Gold is where you find it.

4/15/2002 1:31:39 PM
* Mok T.Y.-r15382 <> [2002-04-15 15:14 +0200]:
> I need some help in converting strings that contain numbers back into
> numeric form. 

No need to convert: Perl doesn't differ between numbers and strings.
Yes, this is completely unlike C, and normally it works as expected.
Just in very few cases you need to choose a sorting algorithm or force
numeric by adding 0 to a putative string.

> Apparently, when I sort string formatted number, the
> arrangement was according to alphanumeric order (eg. 1,
> 10,11,2,20,21,3,30... )

use the right comparator:
	<=> to sort numerically (1,2,10,...) and
	cmp to sort alphabeteically (1,10,2,...).

	@sorted_numerically    = sort {$a <=> $b} @mylist;
	@sorted_alphabetically = sort {$a <=> $b} @mylist;

perldoc -f sort for more examples.

Johannes Franken
Professional unix/network development
4/15/2002 1:45:23 PM
* <> [2002-04-15 15:45 +0200]:

Sorry, cut&paste did it again. In my mail, please replace
> 	@sorted_alphabetically = sort {$a <=> $b} @mylist;
	@sorted_alphabetically = sort {$a cmp $b} @mylist;

Johannes Franken
Professional unix/network development
4/15/2002 2:05:13 PM

Similar Artilces:

setsort for numeric order by with strings that contains numbers ( dw_1.SetSort("convert(numeric(5),ls_number)+ ",A")
Dear all, there is somebody that know how to get a Sort of dw on string field that contain surely a number ? ES. following construct is not good: dw_1.SetSort("convert(numeric(5),string_field)+ " ,A") there is some form to get the numeric sort order (not ascii) ? Thank you in advance Roby You need not convert string to number to do sort. sort will automatically does that for you in the order of first number sort then string sort. "Roberto Lammoglia" <> wrote in message news:3f65b184@forums-1-dub... > ...

how to convert form string to number and back?
Hello, I have to read and write some number-values form/to the ultralite-DB. In the reference-DB (Sybase) the fields are defined as numeric(16,6). I have tried the following in CodeWarrier: 1) Defne the fields in the sql declare section as static char fieldname[17]. This works for download / upload, and showing the values. But if I have to UPDATE the table I get an SQLE_CONVERSION_ERROR 2) Define the fields as DECL_DECIMAL(16,6). Now I can't show the value and can't get the Palm-field and write it to the defined variable because I have only found a sample code to get and...

How to convert text string to numeric string? Pls help.
Dim strApprove As String = "" Dim selIndex As Integer For Each selIndex In rsc.SelectedIndexes strApprove = strApprove + CStr(dg.DataKeys(selIndex)) + "," Next strApprove = Mid(strApprove, 1, ((Len(strApprove) - 1)))  strApprove = 123,234,233,323 (these are id #s) I want to convert strApprove into numeric string(123,234,233) so I can use it in my SQL query.  The ID field is defined as decimal in the database table. I've tried Val() and CLng and didn't get it to work.  Thanks for your help. Dim intApprove as Integer = CType(strApprove, Integer)Community C...

Convert a string to number
Hi. I want to set a value such as 1.5 or 10 to a text box in a report datawindow at the run time. The value will come from the user before he/she runs the report. How do I convert this string in the text box to a number that will be used for further computation at the summary band? I tried number() function, but it requires a real string and refuses to accept a variable or a column name. Thanks in advance for any help. Jian Kuang If the value comes from the user, it would be in the form of a Retrieve Argument. You can refer to the retrieve argument in the computed field for...

Convertion numbers to strings
Hello! I have some numbers in data type "Numeric". The task is to write expression wich combines prefix, number and suffix. The number must have no spare zero's on tale. Linke in example: "NDS 20%" "SN 1.5%" "ANT 0.25%" The slyboot server makes all the numbers with the same length of fract. part. like "20.00000" and I couldn't cope with this for two weeks already. I don't know of a way to do that in SQL Anywhere. -- Jim Egan [TeamPS] Dealer Solutions, Inc. Houston, TX See you at the Powersoft User Confer...

Converting a Numeric/String
OK, I know this is easy, but I am having problems with it.  I have a value in the database (e.g. "27372581") and I am trying to figure out how todisplay it as "27,372,581"How is this done?Karls------------------------------------'Old and wrinkled is not what I expected to become when I grew up!' I figured it out:The FormatNumber() function returns a value formatted as a number. Its general format is shown below.FormatNumber(value [, trailing digits] [, leading digit] [, parentheses] [, group digits]) value is any expression that produces a number;trailing digits is an intege...

Converting a string to a number
Hello everyone, first post and all that, i got a bit of a problem. First off, the DB information: id: autonumber score: text Both these feilds in the database are numerical, however, the score is used as a text feild, the id an autonumber. When i use a querystring to pass the score over to another page, so that the page produces only information with that perticular score matching, it works. When i try to use the ID number, i get a case miss match. I can only fathom that this is because its an autonumber. However, i need to keep the DB design as it is, as when i add a ne...

convert string to number
Hello, if I use the sprintf function it would give me a number STRING, but = not number, so I have to trick the string to become number by adding and su= btracting the number with 1. Is there a better way than this ? I want it to= be a number data type and not string.=0A=0Ae.g =0A=0Amy $strNumber =3D spr= intf("%04d", 123);=0Amy $number =3D $strNumber + 1 - 1; # to trick Perl to = convert to number datatype instead of string. =0A=0A=0AThanks,=0A=0AWilliam= =0A=0ASend instant messages to your online friends http://uk.messenger.yaho= On Sun, Jun 15, 2008 at 8:09 PM, Wi...

Convert String to Number
I am running PB 7.03 build 10047 on Windows 2000. How do I convert a string value to number in the DataWindow script? I can convert number to string using String(ll_value), but how do I do the reverse? The help file says I should be able to use Number(ls_value), but the error checker tells me that is an unknown function. Thanks for your help. dec('123') or long('123') or integer('123') -- Kim Berghall Sisu Group, Inc. remove no_spam. <Scott_Emery> wrote in message news:72D1C6C14C517376005C20...

convert string to number?
Hi, I have a problem where a number read from a file is being treated as a string by perl (I think!). I am using the module RSPerl which is an interface between Perl and the statistical language R. When i read a column of numbers from a file and pass it to the perl/R function i get an "invalid 'type' (character) of argument" error. The reason i think this is a problem on the Perl side is shown by this pseudocode: while(<FILE>){ ... stuff to extract $value from each row ... push(@list1, $value); } @list2 = (100.2, 232.333, 344.2); # these ...

Convert a String to a Number
How can i convert a character to a number, so that the result is only numerical digits, and would always be the same, besides 26 (plus non-alpha characters) if-then statements. like, A = 1 and A always equals 1 so if I had the string:  1234A after converting, I would get the result:  12341 A doesn't necessarily have to = 1, or even a single digit.  It just has to equal a numerical... number. perhaps you can do something like this.  Store your letters in an array A and maintain a cooresponding array B that has the numeric equivalent you would want to repla...

how to convert a number to string in SQL?
I search the help for T-sql, still don't know how to convert a number, for example 12345 to a string with formating like 12,345 Thanks for your help. The best place to do such formatting is in the front end, not at the database level.That being said, you could use a combination of the CONVERT and CAST functions (see CAST and CONVERT) to cast the number as a money type, then convert it to a varchar, and then strip off the decimal point and 2 0's at the end:DECLARE @test intSELECT @test = 12345SELECT REPLACE(CONVERT(varchar(50), CAST(@test AS money), 1),'.00','')Or, you could make use of a ...

Convert formatted string to numeric?
Hi, All I have a datagrid with TemplateColumn as following. Notice the "{0:c}" format the price as $8.90 for 8.90 and  ($7.8) for -7.8     <ItemTemplate>        <asp:Label id=lblPrice runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.price","{0:c}") %>'>        </asp:Label>       </ItemTemplate> on the backend C# code: I need to get the price and do some calculation decPrice = decimal.Parse(lblPrice.Tex...

Help me : Convert a string into a numeric
Hello, I have a string "0600" that i want to convert into a d�cimal 0.6 to write into a file .... I 'm trying to do : li_tmp=Integer(mystring) // with mystring ="0600" li_tmp=li_tmp/1000 But it's wrong Can Somebody Help me ! Thanks try using a decimal datatype instead of integer "Pascal Perrin" <> wrote in message news:t5fEJVk8$ > Hello, > > > I have a string "0600" that i want to convert into a d�cimal 0.6 to write > in...

Web resources about - Convert Number In Strings to Numeric Form - perl.beginners

List of converts to Buddhism - Wikipedia, the free encyclopedia
Ajahn Brahm (born 1951), Religious teacher and student of the late Thai monk Ajahn Chah . Currently he is the abbot of the Bodhinyana Monastery, ...

Facebook Timeline For Pages: 8 Million Converts, 29 Million To Go
... reach to 98 percent of users who liked its page, as well as to double its engagement rate, during a 28-day period. Dr. Pepper hasn’t yet converted ...

Facebook stock roundup: Execs offload more stock, directors convert shares
... Bowles, the former co-chair of the now-defunct National Commission on Fiscal Responsibility and Reform, and Reed Hastings, Netflix CEO, converted ...

How to Convert Leads Into Buying Customers - The 9 Step Sales Process EVERYONE Should Use
... School of Business in Toronto on the topics of Sales and Entrepreneurship. I shared with them the sales process that I find How to Convert Leads ...

Bitcoin : Should I convert my savings to Bitcoin?
Answer (1 of 7): You should think of this question as "Should I invest all my savings in Bitcoin?", and not "Should I have my savings denominated ...

Coordinates - Calculate and Convert a Position on the App Store on iTunes
Get Coordinates - Calculate and Convert a Position on the App Store. See screenshots and ratings, and read customer reviews.

Catholics should not convert Jews, says Vatican, in push against anti-Semitism
... 50 years since the Vatican's repudiation of the concept of Jewish guilt for Jesus' death.  Vatican City: Catholics should not try to convert ...

Opinion: These 5 things made me a happy iPad Pro convert
... like I needed a bigger device. But after three weeks with my iPad Pro, several things have changed my mind, and I’m officially a happy convert ...

$100 device converts all your film to digital photos
... still on film negatives. Today, we've got the perfect Amazon Cyber Week deal for you: A Wolverine F2D Mighty 20MP 7-in-1 Film to Digital Converter ...

"ISIS 'ranks' the women, considering foreign women and converts to be especially 'valuable.' "
"According to French journalist Anna Erelle’s recent exposé , ISIS foreign fighters prefer foreign women and converts because the jihadists find ...

Resources last updated: 12/14/2015 11:11:04 AM