How would I format a second timer? [duplicate] - c#

I am currently building a sales module for a clients website. So far I have got the sale price to calculate perfectly but where I have come stuck is formatting the output to 2 decimal places.
I am currently calling this in a variable so that I can data bind the results to a listview.
Sale = float.Parse(((x.Sale_Price - (x.Sale_Price * (x.Discount_Price / 100))).ToString())),
Can anyone show me how to format the output to 2 decimal places?? Many Thanks!

You can pass the format in to the ToString method, e.g.:
myFloatVariable.ToString("0.00"); //2dp Number
myFloatVariable.ToString("n2"); // 2dp Number
myFloatVariable.ToString("c2"); // 2dp currency
Standard Number Format Strings

The first thing you need to do is use the decimal type instead of float for the prices. Using float is absolutely unacceptable for that because it cannot accurately represent most decimal fractions.
Once you have done that, Decimal.Round() can be used to round to 2 places.

This is for cases that you want to use interpolated strings. I'm actually posting this because I'm tired of trial and error and eventually scrolling through tons of docs every time I need to format some scalar.
$"{1234.5678:0.00}" "1234.57" 2 decimal places, notice that value is rounded
$"{1234.5678,10:0.00}" " 1234.57" right-aligned
$"{1234.5678,-10:0.00}" "1234.57 " left-aligned
$"{1234.5678:0.#####}" "1234.5678" 5 optional digits after the decimal point
$"{1234.5678:0.00000}" "1234.56780" 5 forced digits AFTER the decimal point, notice the trailing zero
$"{1234.5678:00000.00}" "01234.57" 5 forced digits BEFORE the decimal point, notice the leading zero
$"{1234.5612:0}" "1235" as integer, notice that value is rounded
$"{1234.5678:F2}" "1234.57" standard fixed-point
$"{1234.5678:F5}" "1234.56780" 5 digits after the decimal point, notice the trailing zero
$"{1234.5678:g2}" "1.2e+03" standard general with 2 meaningful digits, notice "e"
$"{1234.5678:G2}" "1.2E+03" standard general with 2 meaningful digits, notice "E"
$"{1234.5678:G3}" "1.23E+03" standard general with 3 meaningful digits
$"{1234.5678:G5}" "1234.6" standard general with 5 meaningful digits
$"{1234.5678:e2}" "1.23e+003" standard exponential with 2 digits after the decimal point, notice "e"
$"{1234.5678:E3}" "1.235E+003" standard exponential with 3 digits after the decimal point, notice "E"
$"{1234.5678:N2}" "1,234.57" standard numeric, notice the comma
$"{1234.5678:C2}" "$1,234.57" standard currency, notice the dollar sign
$"{1234.5678:P2}" "123,456.78 %" standard percent, notice that value is multiplied by 100
$"{1234.5678:2}" "2" :)
Performance Warning
Interpolated strings are slow. In my experience this is the order (fast to slow):
value.ToString(format)+" blah blah"
string.Format("{0:format} blah blah", value)
$"{value:format} blah blah"

String.Format("{0:#,###.##}", value)
A more complex example from String Formatting in C#:
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);
This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.

I believe:
String.Format("{0:0.00}",Sale);
Should do it.
See Link
String Format Examples C#

As already mentioned, you will need to use a formatted result; which is all done through the Write(), WriteLine(), Format(), and ToString() methods.
What has not been mentioned is the Fixed-point Format which allows for a specified number of decimal places. It uses an 'F' and the number following the 'F' is the number of decimal places outputted, as shown in the examples.
Console.WriteLine("{0:F2}", 12); // 12.00 - two decimal places
Console.WriteLine("{0:F0}", 12.3); // 12 - ommiting fractions

string outString= number.ToString("####0.00");

I like to use
$"{value:0.##}
It displays two decimals only if there is some value at those places.
Examples:
$"{50.255:0.##} //50,25
$"{50.2:0.##} //50,2
$"{50.00:0.##} //50

private float LimitDecimalPlace(double number,int limitPlace)
{
float result = 0;
string sNumber = number.ToString();
int decimalIndex = sNumber.IndexOf(".");
if (decimalIndex != -1)
{
sNumber = sNumber.Remove(decimalIndex + limitPlace + 1);
}
result = float.Parse(sNumber);
return result;
}

Related

How do i print out the decimal part of a number to a certain number of digits in C Sharp C#

Can someone help me out ?
How do I print out the decimals of a number to a certain number of decimals in C# or should i say, how do you add trailing zeros to meet the specified number.
Example: printing to 7 decimals
5.66 should return 0.6600000
0.123456 should return 0.1234560
A simple way to specify the number of digits is to use a custom formatting string. '0' is a placeholder for a digit to always print, '#' would be an digit to print if relevant. So 7 decimals would be "0.0000000", There are also standard formatting strings that may be useful.
If you are not interested in the whole number part you can just subtract it:
var decimalPart = myValue - (int)myValue;
var str = decimalPart.ToString("0.0000000");
i found the solution. You use the float function.
int double= Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"{num:fn}");
f specifies a float
n specifies the number of decimal places.
so f4 = to 4 decimal places

Add two decimals when the number has even if it has just one decimal (C#)

I want to add two decimals to those numbers who has at least just one decimal. I'm using C# and now I have this instruction but it only returns one decimal position:
string.Format("{0:#,##0.#}", number)
What do I need to put in that instruction to let show the number with two decimal position if the number has at least one decimal? Point that, if the number does not have any decimal, the number is shown with no decimal numbers. That is correct for what I need.
EDIT answer with examples:
4.156,5 has to be 4.156,50
8.150 has to be 8.150
12.230,22 has to be 12.230,22
EDIT 2: Note that I also want to keep the dot separator for thousand digit. So I want to find a string format formula that can include these variants.
Thank you in advance.
Regards
Option 1:
One idea would be to first format with two decimals:
var str = string.Format("{0:#,##0.00}", number);
After this, if the string ends with "(decimalseparator)00", remove this portion:
str = str.Replace(CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator + "00", "")
Not nice, but it works
Option 2:
First multiply by 100 and round to the next integer:
var rounded = (int)Math.Round(100 * number);
Then check if the integer is divisible by 100 and choose one of two format strings:
string.Format(rounded % 100 == 0 ? "{0:#,##0}" : "{0:#,##0.00}", number);

Convert String With Zeros To Decimal

I have a string like this: "000123".
I want to know how to convert this string to decimal but keep the leading zeros. I have used Convert.ToDecimal(), Decimal.TryParse & Decimal.Parse. But all of those methods keep removing the leading zeros. They give me an output: 123. I want the decimal returning 000123. Is that possible ?
No, it's not. System.Decimal maintains trailing zeroes (since .NET 1.1) but not leading zeroes. So this works:
decimal d1 = 1.00m;
Console.WriteLine(d1); // 1.00
decimal d2 = 1.000m;
Console.WriteLine(d2); // 1.000
... but your leading zeroes version won't.
If you're actually just trying to format with "at least 6 digits before the decimal point" though, that's easier:
string text = d.ToString("000000.#");
(That will lose information about the number of trailing zeroes, mind you - I'm not sure how to do both easily.)
So you need to store 000123 in a decimal variable, First of all it is not possible since 000123 is not a Real Number. we can store only Real numbers within the range from -79,228,162,514,264,337,593,543,950,335 to +79,228,162,514,264,337,593,543,950,335 in a decimal variable. No worries you can achieve the target, decimal.Parse() to get the value(123) from the input(as you already did) and process the calculations with that value. and use .ToString("000000") whenever you wanted to display it as 000123

Double to String Format text format

i have the follwing lines of code
double formId=2013519115027601;
txtEditFormID.Text = formid.ToString();
it gives me output
2.0135191150276E+15
if i write
txtEditFormID.Text = formId.ToString("0.0", CultureInfo.InvariantCulture);
it gives me
2013519115027600.0
but i want the label text
2013519115027601
how to do it?
I don't have enough information about the usage of your formId variable.
As it is shown above it seems an error to use a double datatype when there is no decimals to work on. So redefining your variable as a long datatype will be easy and the conversion will be the same.
long formId=2013519115027601;
txtEditFormID.Text = formid.ToString();
Not to mention the added benefit to your code to work with whole numbers instead of floating point numbers.
However, if you want to maintain the current datatype then
txtEditFormID.Text = formId.ToString("R");
The Round Trip Format Specifier
When a Single or Double value is formatted using this specifier, it is
first tested using the general format, with 15 digits of precision for
a Double and 7 digits of precision for a Single. If the value is
successfully parsed back to the same numeric value, it is formatted
using the general format specifier. If the value is not successfully
parsed back to the same numeric value, it is formatted using 17 digits
of precision for a Double and 9 digits of precision for a Single.
Your first option is to use data type as long or decimal . Something else you can do if you want to keep using double is this :
double formId = 2013519115027601;
string text = formId.ToString();
txtEditFormID.Text = text.Replace(".",string.Empty);
this will remove all the '.' chars
There are times where I want calculations handled in double but I want the result displayed as as an int or even rounded amount, so the question isn't so strange (assuming that the given sample is simplified in order to ask the question).
I was going to post sample code for rounding, but it makes more sense to just use the built-in method Math.Round(). You can cast to a long, as mentioned above, but you won't have rounding, if desired (which it usually is, IMHO).
txtEditFormId.Text = ((long)formId).ToString();

Difference between ToString("N2") and ToString("0.00")

What is the difference between ToString("N2") and ToString("0.00")?
From Standard Numeric Format Strings
The number is converted to a string of
the form "-d,ddd,ddd.ddd…", where '-'
indicates a negative number symbol if
required, 'd' indicates a digit (0-9),
',' indicates a thousand separator
between number groups, and '.'
indicates a decimal point symbol.
It would seem that N will include thousands separators, whereas 0.00 will not.
See also Custom Numeric Format Strings
It's all about the decimal places
N2 will work the same way for 500.00, but when you have 5000.00, N2 will display as
5,000.00
instead of
5000.00
See Standard Numeric Format Strings for more information.
Basically, ToString("N2") will use the CultureInfo to format the number. This means that your thousands separator might be different depending on the used CultureInfo. You can also pass the desired CultureInfo if you want.
Both give you two decimal places, but you can see the difference easily if you check larger numbers:
var d = 1234567.89;
for (var i = 0; i < 10; ++i) {
Console.WriteLine(d.ToString("N2") + "\t" + d.ToString("0.00"));
d /= 10.0;
}
outputs
1.234.567,89 1234567,89
123.456,79 123456,79
12.345,68 12345,68
1.234,57 1234,57
123,46 123,46
12,35 12,35
1,23 1,23
0,12 0,12
0,01 0,01
0,00 0,00
Execute code online at dotnetfiddle.net
The thousand separator is an issue. Using "n2" will give you 3,543 where using "0.00" will give you 3543. The comma can break down-stream code that might have to parse that value back to a decimal, especially client-side js.
Here is example to explain
int rupees=567.3423;
string rp=rupees.tostring("N2");
--Answer is rp="567.34";
-- N2 gives upto two decimal records.

Categories

Resources