Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal to string without commas or dots

Tags:

c#

.net

In .NET, I need to convert a decimal amount (money) to a numbers-only string, i.e: 123,456.78 -> 12345678

I thought

var dotPos = amount.ToString().LastIndexOf('.');
var amountString = amount.ToString().Remove(dotPos);

would solve my problem, or at least part of it, but it didn't work as I expected. I'm trying to do this possibly without writing a lot of code and using something already designed for a similar purpose.

like image 444
Fat Shogun Avatar asked Jul 23 '13 12:07

Fat Shogun


4 Answers

You could do it like this:

var amountString = string.Join("", amount.Where(char.IsDigit));

Using the char.IsDigit method will protect you from other unknown symbols like $ and will also work with other currency formats. The bottom line, you don't know exactly what that string will always look like so it's safer this way.

like image 136
Mike Perrenoud Avatar answered Oct 23 '22 04:10

Mike Perrenoud


You say it's an amount, so I expect 2 digits after the decimal. What about:

 var amountstring = (amount * 100).ToString();

to get the cents-value without delimiters?

Or maybe even

var amountString = ((int)(amount * 100)).ToString();

to make sure no decimals remain.

EDIT
If a cast to int isn't quite what you want (It would just ignore any extra decimals, like Math.Floor), you can also use one of the Math.Round overloads, for instance:

var amountString = Math.Round(amount * 100, MidpointRounding.ToEven).ToString();

The MidpointRounding.ToEven (also known as "Banker's Rounding") will round a .5 value to the nearest even value, instead of always to the next higher value.

like image 23
Hans Kesting Avatar answered Oct 23 '22 05:10

Hans Kesting


You don't need casts, you don't need to know where the decimal is, and you certainly don't need Linq. This is literally a textbook-case of Regular Expressions:

Regex regx = new Regex("[^0-9]");
var amountString = regx.Replace(amount, "");

Couldn't be simpler. And you can pass it strings with other odd monetary characters, or any character at all, and all you will get out is the decimal string.

like image 34
Pat Lillis Avatar answered Oct 23 '22 05:10

Pat Lillis


var amountString = amount.ToString().Replace(".","").Replace(",","");
like image 1
Jonesopolis Avatar answered Oct 23 '22 06:10

Jonesopolis