string-formatting

Display Float as String with at Least 1 Decimal Place

允我心安 提交于 2019-11-27 05:24:50
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 :

C# date formatting is losing slash separators

こ雲淡風輕ζ 提交于 2019-11-27 05:14:05
If I do this in C#: Console.WriteLine(DateTime.Now.ToString("ddd M/dd/yy")); I would expect output like this: Wed 6/15/11 But it actually outputs this: Wed 6 15 11 Why are the slashes disappearing? Is there a way to prevent this and have the date outputted in the expected format? Console.WriteLine(DateTime.Now.ToString("ddd M/dd/yy", CultureInfo.InvariantCulture)); Console.ReadLine(); try the above You could also use Console.WriteLine(dateTime.ToString("ddd M'/'dd'/'yy")); That's a possible solution if you're not using the invariant culture as mentioned in other answers here. BaRtEr The

Is there a way to programmatically convert VB6 Formatting strings to .NET Formatting strings?

半城伤御伤魂 提交于 2019-11-27 05:10:53
Does anyone know of a good reference for VB6 format-strings? Does anyone know of a converter from VB6 formatting strings to .NET strings? I'm working on porting a large VB6 code base to .NET. It is a database centric piece of software, and the database itself holds VB6 format-strings which are later loaded and used to display other data in the database. My question, like this article , is how to port this. However the answer chosen for that question isn't adequate for my needs. I'm uncomfortable relying on libraries specifically designed for backwards compatibility with a language I've been

How to generically format a boolean to a Yes/No string?

一个人想着一个人 提交于 2019-11-27 04:44:16
I would like to display Yes/No in different languages according to some boolean variable. Is there a generic way to format it according to the locale passed to it? If there isn't, what is the standard way to format a boolean besides boolVar ? Resources.Yes : Resources.No . I'm guessing that boolVar.ToString(IFormatProvider) is involved. Is my assumption correct? The framework itself does not provide this for you (as far as I know). Translating true/false into yes/no does not strike me as more common than other potential translations (such as on/off , checked/unchecked , read-only/read-write or

Longest common prefix of two strings in bash

纵饮孤独 提交于 2019-11-27 04:24:47
问题 I have two strings. For the sake of the example they are set like this: string1="test toast" string2="test test" What I want is to find the overlap starting at the beginning of the strings. With overlap I mean the string "test t" in my above example. # So I look for the command command "$string1" "$string2" # that outputs: "test t" If the strings were string1="atest toast"; string2="test test" they would have no overlap since the check starts form the beginning and the "a" at the start of

Using .format() to format a list with field width arguments

核能气质少年 提交于 2019-11-27 04:22:21
问题 I recently (finally?) started to use .format() and have a perhaps a bit obscure question about it. Given res = ['Irene Adler', 35, 24.798] and (1) print('{0[0]:10s} {0[1]:5d} {0[2]:.2f}'.format(res)) (2) print('{:{}s} {:{}d} {:{}f}'.format(res[0], 10, res[1], 5, res[2], .2)) work great and both print: Irene Adler 35 24.80 Irene Adler 35 24.80 I didn't know that I could deal with lists as in (1) which is neat. I had seen about field width arguments (2) with the old % formatting before. My

Print floating point values without leading zero

╄→гoц情女王★ 提交于 2019-11-27 04:22:00
Trying to use a format specifier to print a float that will be less than 1 without the leading zero. I came up with a bit of a hack but I assume there is a way to just drop the leading zero in the format specifier. I couldn't find it in the docs. Issue >>> k = .1337 >>> print "%.4f" % k '0.1337' Hack >>> print ("%.4f" % k) [1:] '.1337' You may use the following MyFloat class instead of the builtin float class. def _remove_leading_zero(value, string): if 1 > value > -1: string = string.replace('0', '', 1) return string class MyFloat(float): def __str__(self): string = super().__str__() return

How to get Python to gracefully format None and non-existing fields [duplicate]

不打扰是莪最后的温柔 提交于 2019-11-27 04:03:39
This question already has an answer here: Leaving values blank if not passed in str.format 7 answers If I write in Python: data = {'n': 3, 'k': 3.141594, 'p': {'a': 7, 'b': 8}} print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data)) del data['k'] data['p']['b'] = None print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data)) I get: 3, 3.14, 7, 8 Traceback (most recent call last): File "./funky.py", line 186, in <module> print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data)) KeyError: 'k' Instead of an error message, how can I get Python to more gracefully format the None's and non existent fields? To

How to implement conditional string formatting?

限于喜欢 提交于 2019-11-27 03:48:25
I've been working on a text-based game in Python, and I've come across an instance where I want to format a string differently based on a set of conditions. Specifically, I want to display text describing items in a room. I want this to be displayed, in the room's description, if and only if the item object in question is in the room object's list of items. The way it is set up, I feel that simply concatenating strings based on conditionals will not output as I want, and it would be better to have a different string for each case. My question is, is there any pythonic method for formatting

How to format TimeSpan in XAML

瘦欲@ 提交于 2019-11-27 03:36:57
I am trying to format a textblock which is bound to a TimeSpan property. It works if the property is of type DateTime but it fails if it is a TimeSpan . I can get it done using a converter. But I am trying to find out if there is any alternatives. Sample Code: public TimeSpan MyTime { get; set; } public Window2() { InitializeComponent(); MyTime = DateTime.Now.TimeOfDay; DataContext = this; } Xaml <TextBlock Text="{Binding MyTime,StringFormat=HH:mm}"/> I am expecting the textblock to show only hours and mintes. But it is showing as: 19:10:46.8048860 In .NET 3.5 you could use a MultiBinding