I want to add comma to decimal numbers every 3 digits using c#.
I wrote this code :
double a = 0;
a = 1.5;
Interaction.MsgBox(string.Format("{0:#,###0}", a));
But it returns 2.
Where am I wrong ?
Please describe how can I fix it ?
double a = 1.5;
Interaction.MsgBox(string.Format("{0:#,###0.#}", a));
Here is how to do it:
string.Format("{0:0,0.0}", a)
There is a standard format string that will separate thousand units: N
float value = 1234.512;
value.ToString("N"); // 1,234.512
String.Format("N2", value); // 1,234.51
Its doing it right. #,##0 means write at least one digit and zero decimals and space digit groups with comas. Therefore it rounds 1.5 to 2 as it cant write decimals. Try #,##0.00 instead. You'll get 1.50
Try the following format:
string.Format("{0:#,0.0}", a)
Did you tried by this:-
string.Format("{0:0,000.0}", 1.5);
Related
Which string format can convert this:
1 to 0.01
12 to 0.12
123 to 1.23
1234 to 12.34
12345 to 123.45
Inside my xamarin forms if a user types this number to an entry then it will automatically format that number. What is the string format of that?
For example: Text={Binding Price,StringFormat='${0:F0}'}
Seems like you just want division
var result = value / 100m;
Console.WriteLine(result);
--
Additional Resources
Division operator /
You can divide by 100, as others are saying, followed by applying the desired numeric formats.
Just as Michael Randall said above it's simple as that, in addiction you can check if it can be parsed first, something like this:
bool success = decimal.TryParse(value , out number);
if(success)
var result = value / (decimal)100
else
//Handle incorrect user input
I want to display a float as a string while making sure to display at least one decimal place. If there are more decimals I would like those displayed.
For example:
1 should be displayed as 1.0
1.2345 should display as 1.2345
Can someone help me with the format string?
Use ToString(".0###########") with as much # as decimals you want.
This solution is similar to what other are saying, but I prefer to use string.Format.
For example:
float myFloat1 = 1.4646573654;
float myFloat2 = 5;
Console.WriteLine(string.Format("Number 1 : {0:0.00##}", myFloat1));
Console.WriteLine(string.Format("Number 2 : {0:0.00##}", myFloat2));
// Newer Syntax
Console.WriteLine($"{myFloat1:0.00##}";
Console.WriteLine($"{myFloat2:0.00##}";
This would produce :
Number 1 : 1.4646
Number 2 : 5.00
Number 1 : 1.4646
Number 2 : 5.00
Try this:
doubleNumber.ToString("0.0###");
And, for your reference (double ToString method): http://msdn.microsoft.com/en-us/library/kfsatb94.aspx
float fNumber = 1.2345; // Your number
string sNumber = fNumber.ToString(); // Convert it to a string
If ((sNumber.Contains(".") == false) && (sNumber.Contains(",") == false)) // Check if it's got a point or a comma in it...
{
sNumber += ".0"; // ... and if not, it's an integer, so we'll add it ourselves.
}
Looking for:
95,4545454545455 -> 95 %
I tried using:
String resultAsPercentage = result.ToString("##0 %");
But, it shows
9545 %
Then, I solved my problem using regex:
Question: Why my ToString method hasn't worked? And how to fix it to avoid using regex?
Thanks in advance.
As documented on Custom Numeric Format Strings, the % modifier multiplies the value by 100 before inserting the %. It's intended to be used with fractions. To disable this special meaning of %, escape it by preceding it with #"\".
Alternatively, you could take the % out of the format string, and append it manually: result.ToString("##0") + " %".
If you don't care about rounding, you can use the following:
double result = 95.4545454545;
String resultAsPercentage = (int)result + " %";
System.out.println(resultAsPercentage);
Output is: 95 %
Casting to an int drops the decimal places without rounding
You can use thew P(ercentage) format specifier, you need to divide through 100 because the specifier multiplies it by 100:
decimal value = 95.4545454545455m;
String resultAsPercentage = (value / 100).ToString("P0"); // 95%
If you need the space between the value and the percentage symbol you could use this approach:
NumberFormatInfo nfi = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
nfi.PercentSymbol = " %";
String resultAsPercentage = (value / 100).ToString("P0", nfi); // 95 %
One way can be Clone a culture (like InvariantCulture), set it's PercentPositivePattern to 0, divide your value by 100 and get it's string representation using The percent ("P") format specifier with 0 precision and that cloned culture as;
var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.PercentNegativePattern = 0;
Console.WriteLine(((int)95.4545454545455 / 100.0).ToString("P0", clone)); // 95 %
You can see all associated patterns on Remarks section on that page.
You can guaranteed to set PercentNegativePattern property as well for negative values.
I have come up with the following regexp to accept values with a .25 interval or in quarter format, like 1.25, 10.75, 11.50, 12, 13.
Regular Expression
^\d+((\.0+)*|(\.250*)|(\.50*)|(\.750*))$
Example
Accepted Values = 0, 0.25, 0.50, 0.75, 3 , 1.25 , 1.50, 1.75, 5 , 10
Not Accepted Values = 0.15, 0.20, 0.26, 0.30, 1.30, 1.55
I have the following questions;
How can I make it not accept .25, but accept 0.25?
How can I limit the value to the maximum number? I want it to accept up to 15.5.
In my opinion, Regex is not the correct tool for that kind of work. All the values you want to accept are decimal values. Simply parse the entered value as decimal and then check if it's correct regarding your accepted values:
decimal number;
if (Decimal.TryParse(value, out number))
// Check if you're in the correct range
It will be much simpler, and errorproof.
This is the wrong way to do this, but a solution nonetheless:
^((1[0-4]|[0-9])?(\.(25|5|75)?0*)?|15(\.(25|5)?0*)?)$
Demo
Regex r = new Regex("^((1[0-4]|[0-9])?(\\.(25|5|75)?0*)?|15(\\.(25|5)?0*)?)$");
string[] arr = {".25", "17.545", "3.75000", "19.5", "10.500", "0.25"};
foreach(string s in arr) {
if (r.IsMatch(s)) {
Console.WriteLine(s);
}
}
It gives:
.25
3.75000
10.500
0.25
It's not accepting .25 as if you have a \d+ at the beginning which means that you are waiting at least one digital before ".". I think you could change \d+ by the following (0|1)?[1-5]? to accept till 15.
Regex details can be found here.
You can use this regex:
^((?:1[0-4]|[0-9])?(?:\.(?:25|5|75))?0*|15(?:\.(?:25|5)?0*)?)$
Demo: http://regex101.com/r/eQ2pA1/7
^(0|1)?[1-4]?(|\.0+|\.250*|\.50*|\.750*)$ for matching 0-14 numbers and make a | to match with numbers 15, 15.25, 15.50* with the following:
15(|\.0+|\.250*|\.50*)
The final one will be
^(((0|1)?[1-4]?(|\.0+|\.250*|\.50*|\.750*)) | (15(|\.0+|\.250*|\.50*)))$
I think Regex is the wrong way to do it, but if you insist then the following should suit you right.
^(\d|1[0-5]?)((\.0+)*|(\.250*)|(\.50*)|(\.750*))$
I need all values to rounded to two decimal places. So 1.401 should round to 1.40, but Math.Round(value, 2) rounds to 1.4.
How can I force the trailing zero?
1.4 is the same as 1.40 - you just want to display it differently. Use a format string when calling ToString - like value.ToString("0.00")
1.4 == 1.40 the only time you'd ever need a trailing 0 is when you display the number..i.e. format it to string.
.ToString("N2");
The trailing zero is more of a formatting than a value issue, so use
foo.ToString("0.00")
I know this is an old question, but might help someone!
I am using a c# xml class to populate and then serialise to xml. One of the values is a double. If I assign a '7' to the value this gets serialised to '7' when I actually need '7.00'. Easiest way round this was just to do:
foo = doubleValue + 0.00M
And that makes the value 7.00 instead of just 7. Thought this was better then doing a ToString and then parsing it back.
The trailing zero is just a presentation. Math-wise, 1.40 and 1.4 are equivalent.
Use formatting instead to present it with the 2 decimal places:
String.Format("{0:0.00}", 1.4);
or
yourNumber.ToString("0.00");
It has to do with whether you use a decimal or a double.
While internally (as it appears from the Source Code) Math.Round() preserves the trailing zeros even on a double, still the fact that it is saved as a double in memory causes automatically to remove all trailing zeros
So if you do want tailing zeros, you can either use the string display functions to format it as others have answered, or make sure to pass in the original value as a decimal (causing to use internally Decimal.Math.Round which will deal only with decimals), and make sure to not cast the result to a double and also not to save it in a double variable.
Similarly if you have a decimal and you don't want trailing zeros, just cast it to a double (you can either cast the input to Math.Round or the result, it doesn't matter as long as somewhere in the way it is becoming a double).
It is a number (double?), so it doesn't have a trailing zero - you have to make it text and force a trailing zero.
You can use this function instead of round and just use it like you use round function.
import decimal
def printf(x, n):
d = decimal.Decimal(str(x))
d0 = -(d.as_tuple().exponent)
if d0 < n:
print("x = ", x)
else:
d1 = decimal.Decimal(str(round(x, n)))
d2 = d1.as_tuple().exponent
MAX = n + d2
if MAX == 0:
print("x = ", round(x, n))
else:
i = 0
print("x = ", round(x, n), end = '')
while i != MAX:
if i == (MAX - 1):
print("0")
else:
print("0", end = '')
i = i + 1
So you must have something like this.
>>> printf(0.500000000000001, 13)
>>> 0.5000000000000