简体   繁体   中英

Decimal string without decimals, dots or commas in any culture

If I have a simple decimal in C#, and I want to ToString it without any dots, commas or decimals in any culture - how do i do it?

I tried the ToString("N0") with invariantculture which removes decimals, but it adds "." in my language.

What is the best way to do this?

You haven't clarified in the comments yet, but I suspect you want something like this?

3.14 -> 3

5.34543543 -> 5

If that is correct then you simply need to cast your decimal to an int which would strip the precision off and give you just the whole number.

string someString = ((int)someDecimal).ToString();

If you find yourself repeating this logic often you can make a simple extension method to keep it DRY:

public static class DecimalExtensions
{
    public static string ToIntString(this decimal input)
    {
        return ((int)input).ToString();
    }
}

And simply call it like so:

string someString = someDecimal.ToIntString();

Simple fiddle here

EDIT

@HansPassant actually gave the simplest solution in the comments and I feel silly for not remembering:

string someString = someDecimal.ToString("F0", System.Globalization.CultureInfo.InvariantCulture);

This is a much better answer and if Hans posts an answer I suggest marking theirs as the solution.

In addition to maccettura's answer which will only work for numbers between (2^31)-1 and -(2^31)-1. You can use:

decimal.Truncate(decimalToTruncate)

which should work for all values that a decimal can store.

Simple fiddle by maccettura

Decimal.Truncate on MSDN

The simple way is just use Convert.ToInt32("Your Value") instead of .ToString().

So

string result= Convert.ToInt32("3.14").ToString();

It will give you "3" as result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM