LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-17-2008, 07:19 PM   #1
darkangel29
Member
 
Registered: Nov 2004
Location: Puerto Rico
Distribution: Ubuntu 10.04
Posts: 121

Rep: Reputation: 15
How to convert a string to double in C#?


I'm new to C# and I want to know how can I convert a string like "pizza slice $2.50" into a double so I can use the number to do mathematical operations with it?? Thanks in advance.
 
Old 05-18-2008, 07:17 AM   #2
AdaHacker
Member
 
Registered: Oct 2001
Location: Brockport, NY
Distribution: Kubuntu
Posts: 384

Rep: Reputation: 32
Well, the first thing you need to do is get rid of the leading characters so that you have a string containing a number. After that, you can use System.Double.Parse() or, if you're using .NET 2.0, System.Double.TryParse(). The difference is that Parse() returns the double and throws an exception on failure, whereas TryParse() sets the double value in a reference parameter and returns true or false for success or failure. Here's an example:
Code:
string s = "pizza slice $2.50";
// Get rid of the "pizza slice" part
string price = s.Substring(s.IndexOf('$'));
double number;
bool result = System.Double.TryParse(price, out number);
if (result) {
   System.Console.WriteLine("The price is " + number);
} else {
   System.Console.WriteLine("Could not determine the price.");
}
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
C++ String to double conversion americanforest Programming 4 10-23-2007 09:44 PM
string to double cynthia Programming 4 10-12-2004 02:40 AM
C# trouble converting from string to double. exodist Programming 2 02-23-2004 11:38 PM
Float/Double to String? Mega Man X Programming 16 01-03-2004 07:50 PM
java covert double into string iceman47 Programming 10 05-28-2003 10:51 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:23 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration