Friday, June 26, 2009

C# Double Decimal Place using String Format

String Format for Double [C#]

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.

Digits after decimal point

This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.


// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.


// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"

Digits before decimal point

If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.


// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"

Thousands separator

To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.


String.Format("{0:0,0.0}", 12345.67);     // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"


Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).

Following code shows how can be formatted a zero (of double type).


String.Format("{0:0.0}", 0.0);            // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""

Align numbers with spaces

To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.


String.Format("{0,10:0.0}", 123.4567);    // "     123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "

Custom formatting for negative numbers and zero

If you need to use custom format for negative float numbers or zero, use semicolon separator;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.


String.Format("{0:0.00;minus 0.00;zero}", 123.4567);   // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"

Some funny examples

As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.


String.Format("{0:my number is 0.0}", 12.3);   // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3); // "12aaa.bbb3"

Wednesday, June 24, 2009

Wireless cellular network, packet scheduling, multi-user diversity effect, opportunity scheduling

It has been several decades since the existence of wireless cellular network, which has brought tremendous conveniences to the world society with the developments on top. At present, the traditional telecommunications market is gradually merging its business with data together. As a result, the next-generation wireless cellular networks are heading towards the direction of all-IP packet networks. In addition, the proportion that data division business holds within all business of cellular network will become more importantly, which then makes the packet scheduling mechanisms become more important. With an increasing demand for the end-to-end quality of service, and the contradictions of significant increase in data traffic with the limited resources of the wireless resources, such as video, file transfer, and other data services, all of which are challenging the scheduling mechanisms in the network environment. Furthermore, how to improve the wireless cellular network system throughput to meet the requirements of the user's Quality of Service (QoS), how to provide a fair service to all users, have become the major issues which need to be addressed in the packet scheduling mechanisms for wireless cellular network.

The packet scheduling mechanism for the wireless cellular network is based on cross-layer design concept, which will consider all layers to make scheduling decisions. For example, the physical layer, will have a multi-user diversity effect due to varying characteristics(无线衰落信道具有时变特性). Using (exploit) multi-user diversity effect (多用户分集效应) can effectively enhance the data throughput of the wireless cellular system. Scheduling such as the opportunity scheduling, is commonly used in the packet scheduling mechanism for the wireless cellular networks. This thesis mainly focus on the theoretical model of opportunity scheduling and its specific algorithms.

With Regards to the theoretical model of opportunity scheduling, the author has classified and summarized the various existing theoretical models, including the division-level model and flow-level models. In terms of opportunity scheduling performance indicators and the typical opportunity scheduling algorithm in the division-level model and flow-level model of performance evaluation, experiment has also been conducted to analyse the existing methods and results. Finally, the author gives an predicting analysis of the theoretical tools that can be used in future in this area.

Regarding the specific algorithms used in opportunity scheduling, existing algorithms were summarized and compared, including the scheduling algorithm which uses OFDM technology in the wireless cellular network. The author discovered that the traditional method usually pay more attention to improve system throughput, however fails to provide a fair and user-satisfactory QoS. A new algorithm, without the sacrificing of system throughput ,was presented, to ensure the relatively fairness between all users and each user's QoS demand are met.

Sunday, June 21, 2009

C# open folder dialog (FolderBrowserDialog)

In .Net GUI Applications, Interaction with User on selecting files is a very basic topic. In the following code samples, I have demonstrate how to select files ( in comment code), more importantly, give an example code on how to get a folder name form the windows open dialog box. Something Interesting here is that you actually can’t get the folder name easily. (I mean select a folder, you can still select the file then get the full path, which include the folder name) The best option is to use FolderBrowserDialog !

Ok, now here is the sample code. Enjoy.

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
string startupPath = Application.StartupPath;
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
dialog.Description = "Open a folder which contains the xml output";
dialog.ShowNewFolderButton = false;
dialog.RootFolder = Environment.SpecialFolder.MyComputer;
if(dialog.ShowDialog() == DialogResult.OK)
string folder = dialog.SelectedPath;
foreach (string fileName in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly))
//using (OpenFileDialog dialog = new OpenFileDialog())
// dialog.Filter = "xml files (*.xml)|*.xml";
// dialog.Multiselect = false;
// dialog.InitialDirectory = ".";
// dialog.Title = "Select file (only in XML format)";
// if (dialog.ShowDialog() == DialogResult.OK)
// {
// SQLGenerator.GenerateSQLTransactions(Application.StartupPath + Settings.Default.xmlFile);
// }
catch (Exception exc)
MessageBox.Show("Import failed because " + exc.Message + " , please try again later.");


Friday, June 19, 2009

For Daniel and Victorial

Two friends of mine will soon be moving to UK.  As a reader of getting down under forum, I would like them to read this post:


As the British economy hits rock bottom, thousands of skilled workers are looking abroad to start up a brighter, more stable life in a different economy.

Traditionally, Australia and New Zealand have been a favourite destination for British skilled migrants, but it seems now their economies are also feeling the rippling effects of the American and British recessions.

There has been much debate as to whether Senator Chris Evans (Minister for Immigration and Citizenship) would lower the record rates of immigration to Australia in the 2009-10 Budget in response to his country’s prospective financial troubles.

Evans has decided to keep this year’s record 133,000 skilled visas as a ceiling until the Government assesses the country’s economic situation in time for the mid-year Budget.

This means that Australia still has plenty of places for skilled workers to move to Australia, and you could be joining the thirty-odd thousand other Britons moving to Australia permanently every year through the Australian migration program.

Now we all know Australia has a better climate, nicer beaches, and the promise of a more comfortable, outdoor lifestyle than the UK, but, in this economic climate would skilled workers actually be better off by moving from the UK to Australia?

How much money can you earn in Australia compared to the UK

The following is a comparative table showing the median salaries for selected jobs in Australia and the UK, sourced from (updated February 2009).  The results are based on the person having 10-19 years experience in that job, and the Australian salaries have been converted using the tool. 

The following is a comparative table showing the median salaries for selected jobs in Australia and the UK, sourced from (updated February 2009).  The results are based on the person having 10-19 years experience in that job, and the Australian salaries have been converted using the tool.

A quick look at the table suggests the trend for higher salaries in Australia for skilled positions is evident, excluding the rather major difference for solicitors.

Cost of living in Australia versus the cost of living in the uk

A higher salary doesn’t mean much if you are paying higher prices for the everyday basics.  The following table shows the cost of basics as supplied by the Office of National Statistics (ONS) and the Australian Bureau of Statistics (ABS) for December 2008.

Cost of living in Australia versus the cost of living in the uk. A higher salary doesn't mean much if you are paying higher prices for the everyday basics.  The following table shows the cost of basics as supplied by the Office of National Statistics (ONS) and the Australian Bureau of Statistics (ABS) for December 2008

The table shows Australia is not the winner in every case, and in fact, the UK is the cheapest place in the world to buy bread.  Yet, although the overall picture gives the impression that the cost of living in Australia and the UK is vacillating, a closer look shows that the expensive staple items are considerably cheaper in Australia than in the UK, which would keep your wallet plumper for longer.

For example, a family of four that consumes 2kgs of beef a week could save up to £303 after migrating to Australia from the UK, and a person filling up a car with 30L of petrol every week could save up to £280 per year.  These are substantial savings.

Whereas milk, bread and flour may be cheaper to buy in the UK, the items that you need to outlay more cash on a weekly basis (such as meat and petrol) are cheaper in Australia.

The Economist’s Big Mac index makes things loud and clear to understand.  The famous index compares the cost of a Big Mac in hundreds of countries as a way of comparing the cost of living around the world.  During February 2009, the index showed that a Big Mac was cheaper to buy in Australia than in the UK.

A cheaper cost of living coupled with a higher chance of getting a better salary in Australia means that you would have more spending power and an increased cash flow.

Australia property prices compared to the UK

In most countries, an increased cash flow means a higher standard of living and the opportunity of living in a nicer home.

Property prices across Australia have a huge variance, particularly because there is a massive difference between rural, coastal and city houses.  The same can be said for the UK, where just in the city of London, house prices can be almost triple the cost of similar types of houses elsewhere in the UK. 

As a result, it becomes difficult to compare accurately house prices from specific regions in Australia with regions in the UK.  Yet the Reserve Bank of Australia has released a report that shows the trend in housing prices and affordability, called “Some Observations on the Cost of Housing in Australia”, written by the Head of Economic Analysis Department Anthony Richards.

The following table is extracted from this report, which shows that Australia has been better off internationally than its major competitors in terms of income and relative house prices, despite there being a low level of housing accessibility and persistently high level of average housing prices.

Australia property prices compared to the UK, Canada and the United States (US). The Real Estate Institute of Australia (REIA) confirmed in December 2008 that the Australian average median house price reached $447,659 (£203,660) in the September quarter - a decrease of $459,795 from the June quarter - with only Sydney having a median house price above $450,000

The Real Estate Institute of Australia (REIA) confirmed in December 2008 that the Australian average median house price reached $447,659 (£203,660) in the September quarter – a decrease of $459,795 from the June quarter – with only Sydney having a median house price above $450,000.  In the Department for Communities and Local Government live tables, the average median house price in the September quarter for 2008 was sitting at £233,459.

This difference in average house prices and the trend to have better income ratios in Australia and the UK means you would have a great chance of a better lifestyle in Australia, living in a nicer home with an increased cash flow.

The Australian weather compared to the UK

It will come as no surprise that Australia gets far more sun than the UK.  In fact, Australia gets around 300 days of sunshine annually, which is 70% of the year.  Moreover, when the rains come rolling in from the ocean or across the desert plains, it is not something the locals complain about; the tropical storms can give hours of entertainment and can be a quick relief for stifling heat.

See below for a breakdown of how averages of temperature (degrees) compare in UK and Australian cities:

The Australian weather compared to the UK - breakdown of how averages of temperature (degrees) compare in UK and Australian cities

How many public holidays do you get in Australia compared to the UK?

In Australia, be prepared to put your feet up for longer.  In the UK, along with the standard annual leave provided by employers, the Government provides workers eight annual public holidays.  In Australia, most workplaces give the same leave entitlements as UK companies, but the Australian Government has been slightly more generous.  Each state or territory has a different amount of public holidays, but all have at least 10 days off or more.  For example, in Tasmania you’ll be given 21 days off every year, plus your 4 weeks annual leave. 

The following shows the amount of public annual holidays in the UK and each Australian state or territory:

How many public holidays do you get in Australia compared to the UK?

Sound appetising?  It’s advised that you beat the Budget and submit your application before the Australian Government considers restricting its migration program, and before you know it you’ll be enjoying a beer on the beach and soaking up the Australian sun!

Friday, June 12, 2009






有“夫妻相”的男女不一定就能是夫妻。找对像时人们大多要考虑相貌,但绝少有以自己的模样为标准找面相相似的另一半的。相貌上男的英俊,女的妩媚;男的有棱有角,女的楚楚动人,等等,这才是男女追求的目标。真的面貌相像的两口子则很少即便相像,这样的两口子也并不一定就是最好的夫妻。看那些“夕阳红”幸福晚霞中的老夫妻们,面貌相似的见不到几个。看不出“夫妻相”能在一个美满婚姻家庭生活中起到什么作用。即便是天赶地凑出一对“夫妻相”的夫妻,就一定能是幸福美满的夫妻么?生活中的夫妻不是图画上的夫妻,最实际的夫妻幸福应该是性格的相容,心灵的相慰,生活的相互关心,困难面前的相互支撑,富有面前的相互珍惜和提醒。没有这些内涵的夫妻,再相像又能怎么样呢?或许也有这样的相像而又美满的夫妻,但这样的例子毕竟太少了。 真实的社会生活中,在外人看来门当户对、郎才女貌的夫妻同床异梦并不少见;生活几十年,风过了雨过了一朝把手分的夫妻也不让人奇怪。一些夫妻高矮胖瘦俏平不一,但生活里却各有自己的幸福,各有各的快乐,平平安安地度过了一生;有的夫妻打打闹闹大半辈子,到老了儿孙满堂,相携相拥,满面幸福。这些情形,就不是相貌异同所能解释得了的。











5 自我定义型夫妻相



Wednesday, June 10, 2009

Yet Another Android Mobile Phone HelloWorld Tutorial


<?xml version="1.0" encoding="utf-8"?>
android:text="Click Me"
public class helloworld extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        clickMe = (Button)this.findViewById(;
        editText = (TextView)this.findViewById(;
        clickMe.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                editText.setText("Hello world!!!");               
    private Button clickMe;
    private TextView editText;


Saturday, June 6, 2009

DataGridView EditMode EditProgrammatically

Problem: Whenever you want to write your own double click event for datagridview control, chances are, you will actually end up in edit mode. 

How to solve: DataGridView EditMode property.

From the MSDN,

DataGridView EditMode Property : Gets or sets a value indicating how to begin editing a cell.

The catch is:

All DataGridViewEditMode values except for EditProgrammatically also allow a user to double-click a cell to begin editing it.

Aha, that’s why the problem occur!! So, how do i use Edit EditProgrammatically?

MSDN give the following explaination:

Editing begins only when the BeginEdit method is called.

So I implemented the following event handler to call BeginEdit method.

private void dataGridView_ContextMenuViewEditCell(object sender, EventArgs e)

Then use contexmenu to register the event.

new ToolStripMenuItem(Resources.Common_Label_Edit, Resources.Image_16_Edit,
new EventHandler(this.dataGridView_ContextMenuViewEditCell)));

And finnally,  contexmenu only pop up when right click, so focus needs to be set, same as left click.

DataGridView.HitTestInfo hti = this.dataGridView.HitTest(e.X, e.Y);
if (hti.RowIndex >= 0 && hti.RowIndex < dataGridView.Rows.Count)
dataGridView.CurrentCell = dataGridView[hti.ColumnIndex,hti.RowIndex];

Monday, June 1, 2009

Subversion Trac rules tutorial

A guide that I worte for company staff to follow.


  • Use TortoiseSVN client.
  • Our subversion has the usual trunk/branches/tags layout. Never develop on trunk! Do your part in branches and merge it back to trunk.
  • Recommended check in frequency is every hour! Comment is a MUST.
  • Exclude unnecessary files that are not required in compile. (eg, obj, exe) Pay attention to check-in huge files that can’t be re-versioned!
  • ONLY merge changes that can be compiled and tested into truck. ( and reviewed! Will have detailed discussion about this.)
  • Commit changes as a single logical change set for one purpose. Thus all code changes for a single bug fix or enhancement should be checked-in together. This allows one to better follow the history log of changes.
  • Check-in code at the directory level and all changed files, recursively in the directory and subdirectories will be checked in together.
  • Using Trac integrated with Subversion, refer to the Trac ticket in the Subversion check-in comment using a "#" in front of the Trac ticket number (eg. #65). This generates a hyperlink when the Subversion logs are viewed in Trac.
  • The "tags" branches are NOT to be used as working branches but are snapshots of an existing branch. The "tags" are for historical reference such as a release, well tested version or progress milestone.


  • Document project based information in Trac wiki. (eg, Anything that isn't obvious to fresh eyes gets documented on the Trac Wiki.)
  • Spend at least 0.5 hour a day documenting on the Wiki. This should get placed in the "Documentation" category on the time-tracking software.
  • Using Subversion integrated with Trac, refer to the Subversion specific revision in tickets using a “r” in front of the revision number (eg r103). This generates a hyperlink to view the source in Trac.

Google Pagerank 3 NOW

hurry :)

Display Pagerank

I think it won’t be very hard to achieve if you keep publishing original articles.