Java

Math

import java.lang.Math;
public class Program {
public static void main(String[] args) {
double[] values = { 10.1, 10.5, 10.9, 10 };
*// Round some double values.*
for (double v : values) {
*// This Math.round receives a double and returns along.*
long result = **Math.round**(v);
System.out.println(v + *": "* + result);
}
}
}10.1: 10
10.5: 11
10.9: 11
10.0: 10

import java.lang.Math;
public class Program {
public static void main(String[] args) {
float value1 = (float) 10.1;
float value2 = (float) 10.5;
*// Use Math.round on floats.*
int result1 = **Math.round**(value1);
int result2 = **Math.round**(value2);
*// Display results.*
System.out.println(value1 + *": "* + result1);
System.out.println(value2 + *": "* + result2);
}
}10.1: 10
10.5: 11

HashMap

import java.util.HashMap;
public class Program {
public static void main(String[] args) {
*// Place a Double key in this HashMap.*
HashMap<Double, Long> roundCache = new HashMap<>();
double value = *1000.5*;
roundCache.put(value, Math.round(value));
long t1 = System.currentTimeMillis();
*// Version 1: use round.*
for (int i = 0; i < 1000000; i++) {
for (int y = 0; y < 200; y++) {
*// Use Math.round method directly.*
long result = **Math.round**(value);
if (result != 1001) {
return;
}
}
}
long t2 = System.currentTimeMillis();
*// Version 2: use get() to look up a value.*
for (int i = 0; i < 1000000; i++) {
for (int y = 0; y < 200; y++) {
*// Use get.*
long result = roundCache.**get**(value);
if (result != 1001) {
return;
}
}
}
long t3 = System.currentTimeMillis();
*// ... Times.*
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}* 7* ms: Math.round calls
*358* ms: HashMap get calls

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

No updates found for this page.