12. nov. 2009

DecimalFormat and rounding off

Why does DecimalFormat round off wrong?


I have this nice method that can format a double.
You may also specify the number of decimals.

public static String formatNumber(double number, int decimals) {
String pattern = "###,##0";
if (decimals > 0) {
pattern += "." ;
// Add the wanted number of decimals to the pattern
for (int i = 0; i < decimals; i++) {
pattern += "0";
}
}

// Get the English version of the decimalformatter
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(
Locale.ENGLISH);
df.applyPattern(pattern);

return df.format(number);
}


Now I want to run it:

public static void main(String[] args) {
testNumber(1.5, 0, "2");
testNumber(2.5, 0, "3");
testNumber(2.15, 1, "2.2");
testNumber(2.25, 1, "2.3");
}
public static void testNumber(double number, int decimals,
String expected) {
String formatted = formatNumber(number, decimals);
System.out.print("Testing " + number + ", decimals " +
decimals + ", Actual = " + formatted);
if (formatted.equals(expected)) {
System.out.println(" Expected = " + expected);
} else {
System.out.println(" Expected = " + expected +
" <- Not the same!");
}
}


The outcome is:

Testing 1.5, decimals 0, Actual = 2 Expected = 2
Testing 2.5, decimals 0, Actual = 2 Expected = 3 <- Not the same!
Testing 2.15, decimals 1, Actual = 2.2 Expected = 2.2
Testing 2.25, decimals 1, Actual = 2.2 Expected = 2.3 <- Not the same!


What???
It looks like it rounds off completely randomly.
If you look closer to the documentation, you'll find that DecimalFormat uses ROUND_HALF_EVEN.
This means that "Rounding mode to round towards the 'nearest neighbor' unless both neighbors are equidistant, in which case, round towards the even neighbor. "

But I don't want that, I want it to round up where the fraction is >= 0.5, which is ROUND_HALF_UP, but it seems that you can't change the way DecimalFormat is rounding off, so I've found a way to do it.

If you move the fraction, so the rounding off allways is at the first decimal, you can use Math.round which uses ROUND_HALF_UP, and then set back the correct position for the fraction.

Something like:

double pow = Math.pow(10, decimals);
double numberPowed = number * pow;
number = Math.round(numberPowed) / pow;


Now we can format it using DecimalFormat

But we're not yet homefree, because Math.round is returning a Long, which can't hold big numbers like doubles, so we can only do this trick if the number don't get too big!

The complete method now looks like this:

public static String formatNumber(double number, int decimals) {
double pow = Math.pow(10, decimals);
double numberPowed = number * pow;
// Only do it if the number is not too big
// Math.round returns the neastest Long, so it must fit
// inside a long
if (numberPowed < Long.MAX_VALUE) {
number = Math.round(numberPowed) / pow;
}

String pattern = "###,##0";
if (decimals > 0) {
pattern += "." ;
// Add the wanted number of decimals to the pattern
for (int i = 0; i < decimals; i++) {
pattern += "0";
}
}

// Get the English version of the decimalformatter
DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(
Locale.ENGLISH);
df.applyPattern(pattern);

return df.format(number);
}


And we'll get the right outcome:

Testing 1.5, decimals 0, Actual = 2 Expected = 2
Testing 2.5, decimals 0, Actual = 3 Expected = 3
Testing 2.15, decimals 1, Actual = 2.2 Expected = 2.2
Testing 2.25, decimals 1, Actual = 2.3 Expected = 2.3

14. aug. 2009

Two convicted in U.K. for refusal to decrypt data

Two convicted in U.K. for refusal to decrypt data

What will come next?
That you must reveal your banking password?

It seems that the authorities want to look in your diary.

I think it should not be possible to force people to reveal such stuff.

It's fine, that the authorities can get a court-order to see your financial transactions.

25. jun. 2009

27. apr. 2009

28. feb. 2009

Set the default printer using command shell

I want to set my default printer using a command shell, can it be done?


Yes...

Running "RUNDLL32 PRINTUI.DLL,PrintUIEntry /?" gives you a list of what you can do, and this help you set the default printer:
RUNDLL32 PRINTUI.DLL,PrintUIEntry /y /n "hp psc 1200 series"

See: Usage and examples

26. feb. 2009

Pragtfuldt 1-plans rækkehus med god beliggenhed i Ishøj



Pragtfuldt 1-plans rækkehus med god beliggenhed i Ishøj
Den perfekte bolig hvad enten man er ung eller gammel!


Står du og mangler et rækkehus i Ishøj eller kender du nogen der gør, så er dette rækkehus perfekt...

BEMÆRK:
Åbent hus søndag d. 01.03.2009 kl. 13.00 - 13.30,
Bøgelunden 57
2635 Ishøj


Se flere billeder og yderligere oplysninger: Danbolig

7. nov. 2008

Understanding your visitors

Original post

Why are people leaving your site?


For instance, you can use Google Analytics for tracking where people clicked.

28. jun. 2008

Disable Windows XP stamping reading files

Whenever XP reads a file, it stamps the file with the date and time of the access. This feature has its place but is not required for normal use unless you rely on the date of last access for backup purposes, which is a rare requirement for most backups. Putting a timestamp a file that has just been read means that a write access has to be made to disk, so every time a read is executed, a corresponding write is also executed.

At the command prompt, enter the following then reboot;

FSUTIL behavior set disablelastaccess 1

Those of us who read and write English need to take note of the American spelling of the BEHAVIOR parameter.

To turn timestamps back on, repeat the command but replace the 1 with 0.


25. jun. 2008

Reduce Windows shutdown time

To reduce the timeout Windows XP has for unfinished programs, you may edit it in the registry in milliseconds at the location: HKEY_CURRENT_USER\Control Panel\Desktop editing the value WaitToKillAppTimeout.

Ny blog - Fototips

Jeg har oprettet en ny blog som skal handle om fotografering og billedmanipulation.

Se den her: http://fustphoto.blogspot.com

8. apr. 2008

Eclipse Keytool plugin has moved

The Eclipse Keytool I've made, has moved to http://keytool.sourceforge.net

Feel free to download it, and give your comments.
It's also possible to download it as a application just containing Keytool.

Keyfeatures

  • Export certificate, with or without the private key.
  • Create certificate.
  • Create keystore.
  • Open existing keystore.
  • View all available information about every certificate.
  • Open existing certificate. Default with the extension .cer.
  • View list of certificates in a keystore.
  • Handles JKS and PKCS #12.
  • Show which certificate in a keystore where you have the private key.
  • Filemonitoring, to monitor changes in keystores.
  • Default opening a keystore every time Eclipse starts.

27. sep. 2007

Avoid restarting Windows automatically

Somethimes my Windows just restarts - why?


This may be because of a system failure.
Then Windows automatically restarts.

If you want to disable the restarting, the follow this guide.


Windows 2000 or XP
  1. Right-click "This computer" and choose properties.
    Alternatively press Windows-pause.

  2. Choose tab Advanced

  3. Choose startup and recovery

  4. Remove checkmark at "Restart automatically"


Windows Vista
  1. Start

  2. Write 'System, Properties, Advanced' and press enter

  3. Choose startup and recovery

  4. Remove checkmark at "Restart automatically"

28. aug. 2007

Windows XP Performance Tweaks

My Window is running slow -> Tweak it!


Here's a very good article about Windows
XP Performance Tweaks
.

(Click on the article to read the full story)

  1. Graphical User Interface and Themes

  2. Enable ClearType

  3. Disable Last Access Timestamp

  4. Kernel Paging and Cache Tuning

  5. Separate Window Processes

  6. Processor Scheduling

  7. Turn Off the Indexing Service

8. aug. 2007

Disabling Windows autorun for CDRoms

Windows automatically runs autorun.inf - I don't want that


Startup registrationeditor (Press Start - Run - regedit)
Navigate down to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Cdrom
Here you'll have an element Autorun.
Set it's value to 0 (double-click on it).

23. jul. 2007

Introducing continuous integration

How continuous is your integration and what could your team be doing to improve it?

A JavaWorld excerpt from Continuous Integration: Improving Software Quality and Reducing Risk (Addison-Wesley Professional, June 2007)

Read the article.

16. apr. 2007

1 kilobytes is no longer 1024 bytes...

According to Berlingske is 1 kilobytes no longer 1024 bytes as we learned in school...


It's now 1000 bytes - It's easier to remember, and the old definition can still be used.
1024 bytes is now kibibyte or KiB.

The same goes for a megabyte is now a million bytes (10002). If you want to note 10242 it's MiB.

.. and of course same story for gigabytes, terabytes and so on.

See original post:
1 kilobyte er ikke længere 1024 bytes - Viden og sundhed - Nyheder - Berlingske Tidende

16. mar. 2007

Introduction to Java's Reflection

What is and how do I use Java's Reflection?


Have you ever wondered what is Java's Reflection and how do you use it?
If so, you may have interest in reading this article that gives you a brief introduction on the subject with examples.

15. mar. 2007

Digital Security & Privacy - For human rights defenders

Bruce Schneier posted a link to a pdf with 164 pages about Digital Security & Privacy - For human rights defenders.

The book is written by Dmitri Vitaliev and is about:
  • Security and Insecurity
  • Security awareness
  • Threat assessment and the security circle
  • Windows Security
  • Password Protection
  • Information Backup, Destruction and Recovery
  • Cryptology
  • Internet Surveillance and Monitoring
  • Circumvention of Internet censorship and filtering
  • Encryption on the Internet
  • Malicious software and Spam
  • Identity Theft and Profiling
  • ... and more
  • 13. mar. 2007

    From RAW to print (danish text)

    I have made a colorprofile for my monitor, but the printing of images look different!

    The way you can fix that, is by using colorprofile for the printer as well.
    This article tells you how: (a danish site)
    http://www.digitalmagasinet.dk/%5Cshow.asp?ID=1093