bobsyauncle
bobsyauncle

Reputation: 162

Leave only two places past the decimal point C#

My question is similar to this one:

Leave only two decimal places after the dot

However there is an added complexity. The numerical value is suffixed with a unit that can change into anything i.e.

string test = "0.1542 Mol";

or

string test1 = "0.5247 ml";

Essentially, I'd like something that can deal with both situations that can do this:

string test = "0.15 Mol";

and

string test1 = "0.52 ml";

Upvotes: 0

Views: 267

Answers (5)

JohnyL
JohnyL

Reputation: 7132

UPDATE

You can use Regex:

var s = "0.153567 Mol";
var num = Regex.Replace(s, @"^([0-9]+\.[0-9]{2})([0-9]*)(\s+.+)", "$1$3");
// Output: 0.15 Mol

UPDATE 2

If you need to round a number, you still can use Regex (pattern is changed a bit):

string[] nums = { "0.154567 Mol", "0.158963 ml" };
foreach (var num in nums)
{
    var s = Regex.Replace(num, @"^([0-9]+\.[0-9]+)(\s+.+)",
            m => $"{Math.Round(decimal.Parse(m.Groups[1].Value), 2)}{m.Groups[2].Value}");
    Console.WriteLine(s);
}
// Output:
//   0.15 Mol
//   0.16 ml

Upvotes: 1

Grumpy OldMan
Grumpy OldMan

Reputation: 79

I'm not a C# person, but since no one else has answered this for you, I'll try to help, given my experience with other languages. I would suggest the following solution:

Treat the string as a delimited string with the space as the delimiter. Search for the position of the space, copy the left portion to one variable and the right version to another variable. The IndexOf() and subString() methods in C# might be useful here. Then convert the left side variable to a numeric value and convert it back to string with the appropriate precision. Combine that with the right side string and you'll have what you want.

Here's a link to another thread about ways to get the precision that you are desiring:

Formatting a float to 2 decimal places

Upvotes: 0

jscarle
jscarle

Reputation: 1305

You need to split the string then round the value. String.Format ($) will also do that in a single step:

string test = "0.1542 Mol";
string[] testParts = test.Split(' ');
string rounded = $"{Convert.ToDecimal(testParts[0]):0.00} {testParts[1]}";

Fiddle: https://dotnetfiddle.net/EQsJGf

Upvotes: 2

Flori Bruci
Flori Bruci

Reputation: 456

var splittedString = variable.Split(" ");
var number = String.Format("{0:0.00}", splittedString[0]); 
var result = number + " " + splittedString[1] ;

Upvotes: 0

George Kerwood
George Kerwood

Reputation: 1306

You need to first convert your string to a double that you can round, then reformat to text with the addition of your original units:

    string inputText = "0.1542 Mol";
    double inputNumber = Convert.ToDouble(inputText.Split(' ')[0]);
    double outputNumber = Math.Round(inputNumber, 2);
    string outputText = outputNumber + " " + inputText.Split(' ')[1];

Upvotes: 0

Related Questions