Seems like this should be something straightforward, but I haven't been able to get it right. I've looked at http://idunno.org/archive/2004/14/01/122.aspx for reference.
Example:
I would like to print a table of double values, with each double output having 3 decimal precision, and take up 10 spaces (left aligned). Conceptually, I tried something like this, but it only works with precision OR padding, not both:
foreach(line in lines)
{
foreach (double val in line)
{
Console.Write("{0:0.000,-10}", val);
}
Console.WriteLine()
}
Update: I can use padleft/padright in very simple scenarios, if i have more complicated output it becomes not very concise. Is there something similar to sprintf?
Try
double d = 3.14;
Console.WriteLine("{0,10:0.000}", d);
P.S: have a look at this article as a primer on string formatting. Also, string.Format should allow you doing everything sprintf does - and actually more... what else are you trying to do?
useful
|{0,-10:0.00}| => |87,87 | - With "-" => padRight
|{0,10:0.000}| => | 87,878| - Without "-" => padLeft
|{3,-10:0.###}| - ### - prints numbers after decimal "," only if it is meaningful (not 0): 87,8000 =>87,8
Related
This is one of those cases where I assume the solution is on google, but I have no idea what the search term even is. Or even which Tags to use on Stack Overflow.
Situation:
Floats are not precise. A common trick around it, is to use Integers for the math, then shift the decimal point during output:
If you need 4 decimal places of precision for € (not uncommon in finances), you effectively measure and calculate in milli-Euro. Then during output you shift the decimal left, and cut off the last 2 digits:
So a int 1234567 that is stored, retrieved and processes as a int, would print as/stand for "123.45 €" to the normal end user.
Problem:
But how would this interact with localisation? .NET has this awesome part where Parse() and ToString() look at the current Windows Users Culture setting, to figure out what the decimal separator, group separator and group size is today.
There seems to be no fixed point type in .NET, to do the work for me.
Is there some format string combination I could use to say "shift decimal point 4 left into the number, omit last 2 digits)"? F2 would only add two empty 0 past the decimal point for any int. and "1234567.00 €" is a few orders of magnitude off from "123.45 €"
My best idea thus far:
Building my own format string out of the NumberDecimalSeparator, NumberGroupSeparator and NumberGroupSizes from the users culture - but that is just ugly and seems like something I should not be doing. Is there a better day to do it, or is it one of those cases where I have to go for the ugly thing that works?
Maybe something like this
using System.Globalization;
int n = 123456;
string price = "";
string priceW = "";
int i = 0;
foreach(char c in n.ToString())
{
i++;
if(i == n.ToString().Length - 1)
price += ".";
price += c;
}
float rPrice = float.Parse(price, CultureInfo.InvariantCulture.NumberFormat);
priceW = price + "€";
So I'm a complete newb to unity and c# and I'm trying to make my first mobile incremental game. I know how to format a variable from (e.g.) 1000 >>> 1k however I have several variables that can go up to decillion+ so I imagine having to check every variable's value seperately up to decillion+ will be quite inefficient. Being a newb I'm not sure how to go about it, maybe a for loop or something?
EDIT: I'm checking if x is greater than a certain value. For example if it's greater than 1,000, display 1k. If it's greater than 1,000,000, display 1m...etc etc
This is my current code for checking if x is greater than 1000 however I don't think copy pasting this against other values would be very efficient;
if (totalCash > 1000)
{
totalCashk = totalCash / 1000;
totalCashTxt.text = "$" + totalCashk.ToString("F1") + "k";
}
So, I agree that copying code is not efficient. That's why people invented functions!
How about simply wrapping your formatting into function, eg. named prettyCurrency?
So you can simply write:
totalCashTxt.text = prettyCurrency(totalCashk);
Also, instead of writing ton of ifs you can handle this case with logarithm with base of 10 to determine number of digits. Example in pure C# below:
using System.IO;
using System;
class Program
{
// Very simple example, gonna throw exception for numbers bigger than 10^12
static readonly string[] suffixes = {"", "k", "M", "G"};
static string prettyCurrency(long cash, string prefix="$")
{
int k;
if(cash == 0)
k = 0; // log10 of 0 is not valid
else
k = (int)(Math.Log10(cash) / 3); // get number of digits and divide by 3
var dividor = Math.Pow(10,k*3); // actual number we print
var text = prefix + (cash/dividor).ToString("F1") + suffixes[k];
return text;
}
static void Main()
{
Console.WriteLine(prettyCurrency(0));
Console.WriteLine(prettyCurrency(333));
Console.WriteLine(prettyCurrency(3145));
Console.WriteLine(prettyCurrency(314512455));
Console.WriteLine(prettyCurrency(31451242545));
}
}
OUTPUT:
$0.0
$333.0
$3.1k
$314.5M
$31.5G
Also, you might think about introducing a new type, which implements this function as its ToString() overload.
EDIT:
I forgot about 0 in input, now it is fixed. And indeed, as #Draco18s said in his comment nor int nor long will handle really big numbers, so you can either use external library like BigInteger or switch to double which will lose his precision when numbers becomes bigger and bigger. (e.g. 1000000000000000.0 + 1 might be equal to 1000000000000000.0). If you choose the latter you should change my function to handle numbers in range (0.0,1.0), for which log10 is negative.
In c#, I want to force 0s when converting from double to string in case a number is lower than 100, the only challenge is that I want to keep all decimal places. Examples
58.3434454545 = 058.3434454545
8.343 = 008.343
I tried with ToString + a format provider but I'm not certain what's the correct provider for keeping all decimal places
You can use formatter strings for .ToString(), documented here.
To do what you want you can use this as example, noting the maximum digits for double is 17:
double numberA = 58.3434454545;
numberA.ToString("000.##############"); //058.3434454545
double numberB = 8.343;
numberB.ToString("000.##############"); //008.343
This is a rather ass ugly solution but if you wanted the number of decimals to be dynamic you could try something like this:
private string FormatDouble(double dbl)
{
int count = BitConverter.GetBytes(decimal.GetBits((decimal)dbl)[3])[2];
var fmt = string.Concat("000.", new string('#', count));
return dbl.ToString(fmt);
}
Call it like this:
Console.WriteLine(FormatDouble(58.3434454545123123));
Console.WriteLine(FormatDouble(8.3431312323));
And your output would be this:
058.3434454545123
008.3431312323
I'm sure there is a much better way to do this and I'm not sure about performance, but hey it works and you don't have to guess the number of decimals you need, so that's a plus
Making a console application in C sharp to solve expressions in postfix notation by utilizing a stack, such as:
Expression: 43+2*
Answer: 14
What I've done so far:
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string input = "23+";
int counter = 0;
Stack values = new Stack();
while (counter < input.Length)
{
int temp1,
temp2,
answer;
char x = char.Parse(input.Substring(counter, 1));
if ( );
else if (x == '+')
{
temp1 = (int)values.Pop();
temp2 = (int)values.Pop();
values.Push(answer = temp1 + temp2);
}
else if (x == '-')
{
temp1 = (int)values.Pop();
temp2 = (int)values.Pop();
values.Push(answer = temp1 - temp2);
}
else if (x == '*')
{
temp1 = (int)values.Pop();
temp2 = (int)values.Pop();
values.Push(answer = temp1 / temp2);
}
else if (x == '/')
{
temp1 = (int)values.Pop();
temp2 = (int)values.Pop();
values.Push(answer = temp1 * temp2);
}
counter++;
}
Console.WriteLine(values.Pop());
}
}
For the if statement, what can I use as a condition to check if x is a operand?
Is your example input 2, 3, + (which equals 5), or 23, + (which is invalid input)? I'm assuming the former. How, then, would you write two-digit numbers? Your current approach doesn't seem to support this. I think you shouldn't be parsing this char-by-char, but split it into the separate components first, perhaps using a regex that recognizes numbers and punctuation. As a quick example: Regex.Matches("10 3+", #"(\d+|[\+\-\*/ ])") splits into 10, , 3, and +, which can be parsed and understood fairly easily with the code you already have, (spaces should be ignored; they're simply a punctuation I picked to separate numbers so that you can have multi-digit numbers) and int.TryParse (or double, which requires a more complicated regex pattern, see Matching Floating Point Numbers for that pattern) to see if an input is a number.
You should use a Stack<int> to avoid casting and make it compile-time safe.
Surely this is wrong:
((int)Char.GetNumericValue(x) <= 0 && (int)Char.GetNumericValue(x) >= 0)
I think it should be
((int)Char.GetNumericValue(x) <= 9 && (int)Char.GetNumericValue(x) >= 0)
I really think this is more like a code review but well so be it - first: please seperate some concerns - you baked everything into a big messy monster - think about the parts of the problem and put them into seperate methods to start with.
Then: if you cannot solve the hole problem, make it smaller first: Let the user enter some kind of seperator for the parts, or assume for now that he does - space will do just fine.
You can think of how to handle operators without spaces pre/postfixed later.
So try parsing "2 3 +" instead of "23+" or "2 3+" ...
If you do this you can indeed just use String.Split to make your life much easier!
As to how you can recognize an operant: very easy - try Double.TryParse it will tell you if you passed it a valid number and you don't have to waste your time with parsing the numbers yourself
Instead of using a while in there you should use a for or even better a foreach - heck you can even do this with LINQ and [Enumerable.Aggregate][1] and get FUNctional :D
And finally ... don't use this if/then/else mess if a switch does the job ...
You could say that there essentially are no operands. Even digits can be thought of as operators that multiply the top of the stack by 10 and add the digit value; accumulating a value over several digits as necessary. Then you just need an operator for seeding this by pushing a zero to the stack (perhaps a space character for that).
http://blogs.msdn.com/b/ashleyf/archive/2009/10/23/tinyrpn-calculator.aspx
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to determine if a decimal/double is an integer?
I have a unique situation in which all numbers must be saved as double data type in my database, but only in certain conditions is the precision beyond the integer level valuable.
At first, I tried to just use int and then abstract to a new table when these unique fractional occurances would happen, but after doing that for weeks I can see now that it is excessively stupid and wasting my time.
I know that I can turn a double into an int. That is easy. I know how to translate it over. What I do not know is how to TEST for translating it over. I basically wish to come up with a short, easy way to say
Is this number really a double, or is it just an int?
If it is an int (and most of the time, it will be), then I will turn it into one and treat it as such. But due to the uniqueness of the requirements, I have to still save everything in the database as double.
Any ideas? I know this is a newbie question, and I've googled around for several hours and am still left quite confused.
Cast it to an int and see if it's still equal:
if ((int)val == val)
(int)val will truncate any fractional portion.
Note that this may behave unexpectedly if the number is too large to retain complete precision in the double.
double d = ...;
if(d == (int)d)
//is int
else
//is not int
Of course due to some precision issues, this may not work 100% times. You can use
double d = ...;
if(Math.Abs(d - (int)d) < Epsilon) //const double Epsilon = 0.000001;
//is int
else
//is not int
This similar post shows you how to determine if a double or decimal has decimal places or not. You can use this to determine what type it is and then store appropriately.
Accepted answer from that post:
For floating point numbers, n % 1 == 0 is typically the way to check if there is anything past the decimal point.
public static void Main (string[] args)
{
decimal d = 3.1M;
Console.WriteLine((d % 1) == 0);
d = 3.0M;
Console.WriteLine((d % 1) == 0);
}
Output:
False
True
try this
double x = ......
if (Math.truncate(x) == x)
....... (is integer, unless its so big its outside the bounds)