Math.Round, keep decimal place [duplicate] - c#

This question already has answers here:
Formatting a float to 2 decimal places
(9 answers)
Closed 9 years ago.
For example.
Math.Round(2.314, 2) //2.31
Math.Round(2.301, 2) //2.3 , but I want this as 2.30

Numbers don't have any conception of zeroes after a decimal point.
You're actually asking how to convert the number into a string with extra zeroes:
(2.301).ToString("0.00") // "2.30"
See numeric format strings for more detail.
In particular, the 0 specifier will round away from zero.

You want a string formatting of the number:
string val = Math.Round(2.301, 2).ToString("F2");
here's a post on formatting numbers in C#

2.3 and 2.30 are the same thing. If you want the string 2.30 then use .ToString("F2") on the Math.Round function.

2.3 and 2.30 is the same thing from a code perspective. You can display the trailing zero by formatting a string:
string yourString = Math.Round(2.301, 3).ToString("0.00");

The decimal is still there, you're probably just not seeing because when you look at the string representation, by default it will omit trailing zeros. You can overwrite this behavior by passing a format string to ToString():
Console.WriteLine(Math.Round(2.301, 2).ToString("N2")) // 2.30
But of course, if this is just for display purposes, you don't really need to call Math.Round:
Console.WriteLine(2.301.ToString("N2")) // 2.30
Further Reading
Standard Numeric Format Strings
Custom Numeric Format Strings

If you use decimal numbers (their literals end with m, for "money"), you get the behavior you're after. double numbers don't have a concept of significant zeroes the same way that decimals do.
Math.Round(2.314m, 2);
Math.Round(2.301m, 2);
Or if you want to change how you see the numbers, you can use a string format:
Math.Round(2.314, 2).ToString("N2");
Math.Round(2.301, 2).ToString("N2");

Related

how to convert string to decimal number while maintaining the decimal places in C# [duplicate]

This question already has answers here:
Convert string value into decimal with proper decimal points
(6 answers)
Closed 8 years ago.
In C#, I have a custom string "12.10", when I convert it to decimal it is converted as 12.1 but I need it to be 12.10 in decimal also, please help
Below is the code
string Value = nudEngineeringYears.Value + "." + nudEngineeringMonths.Value;
selStaff.EngineeringExperience = Convert.ToDecimal(Value);
There is no difference between a decimal with value 12.1 or value 12.10.
If you want to display the decimal with 2 decimal place, specify a format string in ToString:
myDouble.ToString("0.00");
Well, as math stays
12.1 == 12.10 == 12.100 == ...
etc. However, you can change number's representation as a string by formatting:
12.1.ToString("F2"); // <- return 12.10 (note "2" in formatting string)
12.1.ToString("F3"); // <- return 12.100 etc.
There's no decimal 12.10, only 12.1.
What you're talking about when you say 12.10 is a possible representation of that value.
There's no difference between 12.10 and 12.1 when talking about numbers, but there's a difference between the string "12.10" and the string "12.1".
So don't confuse a number with its representation (which typically only matters in the front end).
If you want to format your value, you create a string representation of it. See Standard Numeric Format Strings.
You seem to confuse the internal/binary representation of a floating point number with its representation when converted to a string.
Internally a float has always about seven places of precission,
a double about 15 places of precission, a decimal even more.
Only when you format such a binary value to a string you may specify the number of places shown. For formatting use .ToString(format) with the format you need. in your case "F2"

Regex to convert string number to currency [duplicate]

This question already has answers here:
Currency format for display
(8 answers)
Closed 8 years ago.
I have a string filed which holding the dollar amount. What I want to do is process the string and covert in actual currency.
Example:
Possible incoming string;
80
1000.00
1000.0
-100
Desired Outputs are;
100.00
1,000.00
-100.00
How can I format the string with regex and covert it to the output I want?
It's not really clear what you mean by actual currency, but I'm assuming you just want a string that looks like the samples you've posted. Keep in mind that the decimal type (the type best suited to represent currency) doesn't have any actual formatting information.
You'll have to parse the string using decimal.Parse, then convert the value back to a string to get it into the desired format.
For example:
public string Format(string input)
{
decimal value = decimal.Parse(input);
return value.ToString("#,#.00");
}
// usage: Format("1000.0")
Example: https://dotnetfiddle.net/P7psPC
However if you're dealing with currency you can just use the C format specifier:
value.ToString("C");
This would output the following for your sample inputs:
$80.00
$1,000.00
$1,000.00
($100.00)
There isn't a real currency converter in Microsoft .Net Framework, so you have to work within the constraints provided, which is decimal. The closest you can get to your decimal being defaulted to money would be:
decimal amount = 0.00m
The m at the end is declaring that this decimal will represent money. Which when added will provide basic rounding as if it were money.
However the easiest approach would be how Andrew Whitaker did the conversion. The only thing I would add, is that when you utilize:
value.ToString("#,##0.00"); // Output: 0.96
value.ToString("#,#.00"); // Output .96
value.ToString("0.##"); // Output 0.6
To clarify the conversion with ToString(); for the decimal.

Object.ToString() returning erroneous value [duplicate]

This question already has answers here:
Double string.format
(5 answers)
Closed 9 years ago.
If my Object value is for example 1.0, .ToString() is returning 1 and not 1.0.
But if the value is for example 1.5, .ToString() returns 1.5.
Why this behaviour in c#?
NOTE: Object is a Double Value in this case.
It's not "erroneous", it is the default format of the actual data type.
If you want it to always be 1.0, then you need to format it as so.
String.Format("{0:0.0}", myObject);
or
((double)myObject).ToString("0.0");
Why would 1.0 return 1.0 and not say 1.00? 1.23 will return two decimal places as well, right?
C# (and my guess is most other languages as well) will print out decimal places, if they are significant. A bunch of zeroes after the decimal point are not significant, they don't change the value of the number.
It's because Double.ToString() uses the "G", Generic Format, specifier by default. This means that numbers are converted to their most compact form, including this rule:
The result contains a decimal point if required, and trailing zeros
after the decimal point are omitted.
Source: MSDN: Standard Numeric Format Strings
please check the documentation.
http://msdn.microsoft.com/en-us/library/3hfd35ad(v=vs.110).aspx
this is the expected result.
Try value.ToString("F1")
Standart Numeric Formats

format number in C# [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number
How to format a number 1234567 into 1,234,567 in C#?
For format options for Int32.ToString(), see standard format strings or custom format strings.
For example:
string s = myIntValue.ToString("#,##0");
The same format options can be use in a String.Format, as in
string s = String.Format("the number {0:#,##0}!", myIntValue);
Do note that the , in that format doesn't specify a "use a comma" but rather that the grouping character for the current culture should be used, in the culture-specific positions.
You also do not need to specify a comma for every position. The fact that there is a comma in the format string means that the culture-specific grouping is used.
So you get "1 234 567 890" for pl-PL or "1,23,45,67,890" for hi-IN.
var decimalValue = 1234567m;
var value = String.Format("{0:N}", decimalValue); // 1,234,567.00
or without cents
var value = String.Format("{0:N0}", decimalValue); // 1,234,567
Try
String.Format("{0:##,####,####}", 8958712551)
For Examples have a look at http://www.csharp-examples.net/string-format-double/
Using your current locale's thousands separator:
int n = 1234567 ;
n.ToString("N0");
Or, use the overload to ToString, which takes the culture as a parameter.
string formatted = string.Format("{0:##,#}", 123456789);
It depends on the culture of your computer. Some countries use commas, some countries use dots. On my computer the output was: 123.456.789

Convert float to string with comma and dot

I have a nullable float. The internal decimal places can be separated with dot or comma e.g. 1.2 or 1,2. I need this float as a string to compare it to a Regex. If I use the Convert.toString method, the float with the comma is 12 and not 1.2. How can I convert a float to String without loosing the comma or the dot? I alredy tried to convert it with diffrent cultures.
Thanks for your help
A solution for this can be the following:
float? num = 1.2f;
string floatAsString = string.Format("{0:f}", num.Value);
Maybe you need to check if the HasValue property is true before you use the value. For more examples: http://alexonasp.net/samples/stringformatting/
String.Format() function with mask. But can you convert your strings to numbers rather than your numbers to strings, for purposes of the comparison? Does it have to be a regex comparison?
Try:
string s = yourFloat.ToString();
Using the invariant culture is recommended if you want to be sure that your output will be in the correct form, but I'd be surprised if there were a culture which doesn't output a comma or a dot.
I would also suggest not using regular expressions to validate the value of a float.
Are you certain that the textbox allows both "." and "," as a decimal-separator (as opposed to a grouping character, also known as a thousands-separator)?
When you are certain that you only get decimal separators and no grouping characters, replace any "," with a "." before using TryParse with an InvariantCulture to convert the string to a float.
OR use the same culture in the code as on the client side, so both will use the same decimal separators.
As others mentioned, a float doesn't have the concept of various decimal separators.
Ok I solved the problem. I did in my xaml a converter which only allows to enter values with commas as separator, so I dont need any checks if there are only two internal decimal places. Thanks for your help
If it's a WinForm Application, there's a static variable Application.CurrentCulture.NumberFormat.NumberDecimalSeparator.
Depending on it's value you get different results when converting ToString().
Try manipulating this parameter to achieve necessary result.

Categories