Whats the best way to format this number? - c#

I have a double and I want to format it with the following rules:
If there are no decimal places show just the number (see 100 example below)
If there are any decimal places show 2 decimal places
So, as a few examples:
100 --> 100
99.958443534 --> 99.96
99.1 -> 99.10

You could check if its a whole number, the use the type of formatting based on that:
string res = string.Format(((number % 1) == 0) ? "{0:0}" : "{0:0.00}", number);

What about:
var a = 100;
var b = 99.95844354;
var aAnswer = a.ToString("0.##"); //aAnswer is "100"
var bAnswer = b.ToString("0.##"); //bAnswer is "99.96"

You can use:
decimal a = 99.949999999M;
Math.Round(a, 2); // Returns 99.95

Related

How to truncate a number to a fixed size without rounding when displaying it with Console.WriteLine()

I'm trying to format a number in a very specific way when displaying it, I've tried messing around with String.Format but couldn't find a way to make this work exactly as I needed.
For example, let's way that I have a variable of type Double with the value "123459.7889" and that I want to format it as "459.788" (000.000) but only during Console.WriteLine() and without rounding or changing the internal value of the number. The full value of the number would not show up and it should technically "overflow" the string because it should only print the first 3 numbers to the left of the decimal point.
Here are some example inputs and example outputs:
12345.678 formatted to "000.000" would become 345.678
1000000.678 formatted to "000.000" would become 000.678
1.777888 formatted to "000.000" would become 001.777
99999.9 formatted to "000.000" would become 999.900
Basically, no matter the internal size of the number, the formatted output should always be the 3 numbers to the left of the decimal point and the 3 numbers to the right of the decimal point with zeros to replace the missing spaces if there's any.
I've tried looking at the examples on the C# documentation and found this:
double value = 123459.7889;
string result = String.Format("{0,8:00000000} {0,8:00000000.000}", value);
Console.WriteLine(result);
But it doesn't work exactly like I needed it to. When running it the numbers are rounded so it becomes 00123459.789 instead of 00123459.788 for example and if the number grows it no longer stays at that fixed size.
try this:
double value = 123459.7889;
Console.WriteLine((Math.Truncate(Math.Abs(value) % 1000) + double.Parse((Math.Round(Math.Abs(value), 3, MidpointRounding.ToZero) -
Math.Truncate(Math.Abs(value))).ToString(".000"))).ToString("000.000"));
value= 123459.7889; result=345.678
value= 1000000.678; result=000.678
value= 1.777888; result=001.777
value= 99999.9; result=999.900
value= 152; result=152 .000
value= -100.02; result=100.020
value= 10.0005; result=010.000
We can use PadLeft and PadRight to fill up zeros when value characters are not enough.
Implementation:
static void Main(string[] args)
{
double value = 1.12;
string valueStr = value.ToString().Replace("-", ""); // convert to string
// check if value does not contain decimal and add
if (!valueStr.ToString().Contains("."))
valueStr += valueStr + ".0"; // add decimal part
var arr = valueStr.ToString().Split(".");
string intValue = arr[0]; //1
intValue = intValue.PadLeft(3,'0'); //001
intValue = intValue.Substring(intValue.Length - 3, 3); //001
string decimalValue = arr[1]; //12
decimalValue = decimalValue.PadRight(3,'0'); //120
decimalValue = decimalValue.Substring(0, 3); //120
string result = $"{intValue}.{decimalValue}";
Console.WriteLine(result);
}
Result:
12345.678 > 345.678
1000000.678 > 000.678
1.777888 > 001.777
99999.9 > 999.900
152 > 152.000
-100.02 > 100.020
-10.0005 > 010.000
You shouldn't need to convert to string, nor should you rely on splitting on a character that may or may not be the decimal character in the language you are running. You can do all the calculations on the numbers and then format the output without allocating any strings except for the result.
public static string FormatNumber(double number)
{
int first = ((int)number)%1000;
int second = (int)Math.Truncate((number-(int)number)*1000)%1000;
return $"{first:000}.{second:000}";
}
static string Format(double number)
{
return string.Format("{0:N3}", number % 1000).PadLeft(7,'0');
}
How it works:
Remove the upper digits using modulus (%)
Format to three decimal places using a format string
Pad left using PadLeft()
Full example:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var tests = new Dictionary<double,string>
{
{ 12345.678D, "345.678" },
{ 1000000.678, "000.678" },
{ 1.777888, "001.778" },
{ 99999.9, "999.900"}
};
foreach (var pair in tests)
{
Console.WriteLine("Expected: {0} Actual: {1}", pair.Value, Format(pair.Key));
}
}
static string Format(double number)
{
return string.Format("{0:N3}", number % 1000).PadLeft(7,'0');
}
}
Output:
Expected: 345.678 Actual: 345.678
Expected: 000.678 Actual: 000.678
Expected: 001.778 Actual: 001.778
Expected: 999.900 Actual: 999.900
Fiddle
try this
int i = value.ToString().IndexOf(".");
string result = string.Concat(value.ToString().Substring(i - 3, 3),".", value.ToString().Substring(i + 1, 3));
Console.WriteLine(result);

C# formatting a decimal value to places of decimal [duplicate]

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.
}

Show double as percentage without decimals with ToString method

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.

c# How do I format a double to a string and only show decimal digits when necessary?

I found this question in StackOverFlow but it didn't solve my problem.
How do I format a double to a string and only show decimal digits when necessary?
Weight
0.500
18.000
430.000
by the solution in above url my result show in this form:
Weight
0.5
18
430
and my problem is in decimal digits, I want show decimal digits in 3 digit,like this:
Weight
0.500
18
430
You can use Digit placeholder # with Zero placeholder 0 after dot . in string format.
string num = d % 1 == 0 ? d.ToString(".###") : d.ToString(".000");
Digit placeholder
Replaces the pound sign with the corresponding digit if one is
present; otherwise, no digit appears in the result string.
Zero placeholder
places the zero with the corresponding digit if one is present;
otherwise, zero appears in the result string.
This msdn article Custom Numeric Format Strings explains how the number could be formated.
I think you can't do what you want with single string.Format(). So you can use a clause:
if(weight % 1.0 > 0){
string.Format("{0:0.000}", weight)
}
else {
string.Format("{0:0}", weight)
}
Or even better:
string.Format(weight % 1.0 > 0 ? "{0:0.000}" : "{0:0}", weight)
EDIT: Sorry missed a bit =))
EDIT: If you need to floor result you can use:
string.Format(weight % 1.0 >= 0.001 ? "{0:0.000}" : "{0:0}", weight)
Try
num.ToString("G3") // for 3 significant digits
http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
You can use like below method:
Usage:
string format1 = GetFormat(123.4567);
string format2 = GetFormat(123.45);
string format3 = GetFormat(123.0);
//format1 = 123.46
//format2 = 123.45
//format3 = 123
private static string GetFormat(double d)
{
string format;
if (d == Convert.ToInt32(d))
format = string.Format("{0:0.##}", d);
else
format = string.Format("{0:0.00}", d);
return format;
}
For more information:
http://csharpexamples.com/c-string-formatting-for-double/
http://msdn.microsoft.com/en-us/library/vstudio/0c899ak8%28v=vs.100%29.aspx
I found the solution:
string[] strList = Weight.ToString().Split('.');//or ',' for diffrent regions
if(strList[1] == "000")
str = string.Format("{0:#,0.########}", b);
thank you:)

decimal ToString formatting which gives at least 1 digit, no upper limit

How to format a decimal in C# with at least one digit after the decimal point, but not a fixed upper limit if specified more than 1 digit after the decimal point:
5 -> "5.0"
5.1 -> "5.1"
5.122 -> "5.122"
10.235544545 -> "10.235544545"
Use ToString("0.0###########################").
Some notes:,
There are 27 #s in there, as the decimal structure can accommodate precision up to 28 decimal places.
The 0 custom specifier will cause a digit to always be displayed, even if the value is 0.
The # custom specifier only displays a value if the digit is zero and all of the digits to the right/left of that digit (depending on what side of the decimal point you are on) are zero.
You will need to insert as many # after the first 0 to the right of the decimal point to accommodate the length of all the values you will pass to ToString, if you will only have precision to 10 decimal places, then you need nine # (since you have the first decimal place to the right handled by 0)
For more information, see the section of MSDN titled "Custom Numeric Format Strings".
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var a = 5m;
var b = 5.1m;
var c = 5.122m;
var d = 10.235544545m;
var ar = DecToStr.Work(a);
var br = DecToStr.Work(b);
var cr = DecToStr.Work(c);
var dr = DecToStr.Work(d);
Assert.AreEqual(ar, "5.0");
Assert.AreEqual(br, "5.1");
Assert.AreEqual(cr, "5.122");
Assert.AreEqual(dr, "10.235544545");
}
}
public class DecToStr
{
public static string Work(decimal val)
{
if (val * 10 % 10 == 0)
return val.ToString("0.0");
else
return val.ToString();
}
}
Func<decimal, string> FormatDecimal = d => (
d.ToString().Length <= 3 ||
!d.ToString().Contains(".")) ? d.ToString("#.0") : d.ToString()
);

Categories

Resources