Muhammad Ali Dildar
Muhammad Ali Dildar

Reputation: 1527

How to split a string if it contains period (.)?

I am taking numerical input from a text box. I want to check

if(textBox1.Text.Contains("."))

like 55.37

then split the string in two parts/strings.

  1. First part before period (55)
  2. Second part after the period (37)

Upvotes: 4

Views: 32082

Answers (7)

Bjorn Coltof
Bjorn Coltof

Reputation: 509

Use the following:

textBox1.Text.Split('.')

Upvotes: 0

nillls
nillls

Reputation: 623

if (!textBox1.Text.Contains('.'))
    return;

var parts = textBox1.Text.Split('.')

should do the trick.

Upvotes: 2

VMykyt
VMykyt

Reputation: 1629

In case there is a chance your code will be executed on OS with non-windows localization please use:

var separators = new[] {CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator};
var parts = textBox1.Text.Split(separators, StringSplitOptions.None);

It looks too verbose but it may be hard to understand why your code works on your machine (with dev environment) but don't on customers.

Upvotes: 2

Ashok Padmanabhan
Ashok Padmanabhan

Reputation: 2120

use Split method

dim s as string = textbox1.text
s.split(".")

Upvotes: 0

Glory Raj
Glory Raj

Reputation: 17701

use string.Split method

   string[] a = textBox1.Text.Split('.'); 


   string b = a[0];
   string c = a[1];

Upvotes: 4

Marco
Marco

Reputation: 57593

Use this:

string[] ret = textBox1.Text.Split('.');

Then you can do

if (ret.Length != 2) // error ?!?

ret[0] is integer part
ret[1] is fractional part

Upvotes: 20

Matteo Mosca
Matteo Mosca

Reputation: 7448

var splitted = textBox1.Text.Split('.');

The result will be an array of strings. In your sample, the array will have 2 strings, 55 and 37.

Upvotes: 4

Related Questions