Dave's Brain

Browse - Programming Tips - How do I convert a text (ASCII) string to an integer?

Date: 2009nov26
Language: perl

Q.  How do I convert a text (ASCII) string to an integer?

A.  This does the trick;

$text = '123'; $n = $text + 0;
But you should check that $text is a valid number. Attempts to turn non-numbers (eg 'hello') into numbers gives you 0. This function gives undef for non-numbers.
sub asciiToInt($) { my($text) = @_; my($n); if ($text =~ m/^\d+$/) { $n = $text + 0; } return $n; }
There is also hex() and oct() for converting base 16 and 8 numbers strings into numbers.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.