Java decimalFormat RoundingMode - java

I need to archive this: (basically num1 * num2 = num3 and num1 and num2 are given)
1) 10.62 * 4.0 = 42.48
2) 14.89 * 8.5 = 126.56
3) 13.21 * 6.0 = 79.26
4) 16.55 * 7.35 = 121.64
5) 18.62 * 9.0 = 167.58
6) 9.47 * 15.3 = 144.89
7) 6.58 * 3.0 = 19.74
8) 18.32 * 5.4 = 98.93
9) 12.15 * 2.9 = 35.24
10) 3.98 * 4.8 = 19.10
This exercise is to practice formatting/rounding string/number.
So I used:
DecimalFormat decimalFormat = new DecimalFormat(".00");
System.out.println(decimalFormat.format(num3));
and got everything right but the 9) 12.15 * 2.9 = 35.24 , I got 35.23 instead of 35.24
The default RoundingMode of DecimalFormat is HALF_EVEN, if I use RoundingMode.UP I will get this right 35.24 but the others results will be messed so I am stuck...
What should I use in order to get the expected result?

Using RoundingMode UNNECESSARY, will solve your problem. Additionally you can catch exceptions and specify output manually if needed.

Related

How to perform arithmentic operation in delayExpression in #Backoff (Spring-retry)

I want to take delay time in minutes from ENV variable. How to convert minutes into ms in expression string?
#Backoff(delayExpression = "${delay_in_minutes:2} * 60 * 1000",
maxDelayExpression = "${max_delay_in_minutes:10} * 60 * 1000",
multiplierExpression = "${multiplier:2.0}")
Use SEPL(Spring expression language) like below:
#Backoff(delayExpression = "#{${delay_in_minutes:2} * 60 * 1000}",
maxDelayExpression = "#{${max_delay_in_minutes:10} * 60 * 1000}",
multiplierExpression = "${multiplier:2.0}")

Get the real SD Card available free space

Any idea of how I can read/get the real amount of free space on a sd card? I'm running on Android 4.3. I have tried all possible things to read it correctly, however I'm getting something a bit over twice the real free space.
Now I've tried the classic
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
using the API 18 getAvailableBlocksLong and other getBlockSizeLong and still the same result.
The only thing that works (but it's not what I need) is the shell command df. I also tried the get usable free space functions with the same result. And this thing doesn't happen on my device only, but on all devices that I try the code.
Use this:-
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
{
#SuppressWarnings("deprecation")
long sdAvailSize = (long)stat.getAvailableBlocksLong() * (long)stat.getBlockSizeLong();
} else
{
#SuppressWarnings("deprecation")
double sdAvailSize = (double)stat.getAvailableBlocks() * (double)stat.getBlockSize();
}
try doing this:-
double gigaAvailable = sdAvailSize / 1073741824;
If this didn't worked then change getAvailableBlocks() to getBlockCount().
you can also try this:-
/**
* #return Number of gega bytes available on External storage
*/
public static long getAvailableSpaceInGB(){
final long SIZE_KB = 1024L;
final long SIZE_GB = SIZE_KB * SIZE_KB * SIZE_KB;
long availableSpace = -1L;
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
return availableSpace/SIZE_GB;
}
Copied from here :)
Hope it helps.

Type mismatch after running

package skater;
import java.io.*;
import java.util.*;
public class TestSkater
{
public static void main(String[]args) throws IOException
{
Scanner sc = new Scanner(new File("C:/pairs.txt"));
String name1 = null, name2 = null, Country = null;
double [] Technical = new double [8];
double [] Performance = new double[8];
try {
while(sc.hasNext())
{
name1=sc.nextLine();
name2 = sc.nextLine();
Country = sc.nextLine();
for (int t = 0; t<Technical.length; t++)
{
Technical[t] = sc.nextDouble();
}
for(int y = 0; y<Performance.length; y++)
{
Performance[y] = sc.nextDouble();
}
// Skater [] skaters = new Skater[20];
Skater S1 = new Skater(name1,name2,Country,Technical,Performance);
System.out.println(S1);
sc.nextLine();
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.out.print("Bad program");
}
}
}
Whenever I run my code without the try and catch I get an InputMismatchException. It's reading from a file that has all the names of the teams with their scores and countries. It's formatted like this:
smith
jones
australia
4.2 5.1 3.8 2.9 5.0 4.6 4.9 4.3
4.9 4.8 5.8 3.8 4.9 4.6 5.0 4.5
lennon
murray
england
2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8
3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8
I know that the nextLine() is telling it to look at the next line of data, And the nextDouble() that I am using for the arrays Performance and Technical, is telling it to look at the next double in line.
I can't figure out why it is giving me this error. I think it's because when it moves onto the first name of the next team it is still seeing it as a double from the array Performance, but I can't figure out how to fix that problem.
It's hard to say for sure without knowing what the Scanner functions (nextLine, nextDouble) are really doing and the exact format of the file you area reading.
Assuming that:
nextLine reads text to the end of line
nextDouble reads and parses text to the next break/space
Then, by the way you are reading the input, I assume it's in the format:
Name1
Name2
Country
0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0
0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0
If the assumptions are correct and that's not the format of the input then there's your problem.
If you are sure that the nextLine text entries are being read fine then an option may be to read the line as a string, split on space (or comma, or semicolon or whatever seperates them) and parse them yourself e.g.
string[] tmp = sc.nextLine().split(' ');
for(int t = 0; t<Technical.length; t++)
Technical[t] = Double.parseDouble(tmp[t]);

Base64 encoding vs Ascii85 encoding

My project at work is using the Jackson JSON serializer to convert a bunch of Java objects into Strings in order to send them to REST services.
Some of these objects contain sensitive data, so I've written custom serializers to serialize these objects to JSON strings, then gzip them, then encrypt them using AES;
This turns the strings into byte arrays, so I use the Base64 encoder in Apache commons codec to convert the byte arrays into strings. The custom deserializers behind the REST interfaces reverse this process:
base64 decode -> decrypt -> decompress -> deserialize using default Jackson deserializer.
Base64 encoding increases the size of the output (the gzip step in serialization is meant to help ameliorate this increase), so I checked Google to see if there was a more efficient alternative, which led me to this previous stackoverflow thread that brought up Ascii85 encoding as a more efficient alternative -
Base64 adds 33% to the size of the output, Ascii85 adds 25% to the size of the output.
I found a few Java Ascii85 implementations e.g. Apache pdfbox, but I'm a bit leery to use the encoding - it seems like hardly anybody is using or implementing it, which might just mean that Base64 has more inertia, or which may instead mean that there's some wonky problem with Ascii85.
Does anybody know more on this subject? Are there any problems with Ascii85 that mean that I should use Base64 instead?
Base64 is way more common. The difference in size really isn't that significant in most cases, and if you add at the HTTP level (which will compress the base64) instead of within your payload, you may well find the difference goes away entirely.
Are there any problems with Ascii85 that mean that I should use Base64 instead?
I would strongly advise using base64 just because it's so much more widespread. It's pretty much the canonical way of representing binary data as text (unless you want to use hex, of course).
ASCII85 is a nice encoding to use to save that extra bit of space. But it outputs many characters that would need to be escaped if naively sent over HTTP. Base64 encoding has a variant that can be sent over HTTP without any escaping.
Here's a javascript ASCII85 encoder in case anyone needs to try:
// By Steve Hanov. Released to the public domain.
function encodeAscii85(input) {
var output = "<~";
var chr1, chr2, chr3, chr4, chr, enc1, enc2, enc3, enc4, enc5;
var i = 0;
while (i < input.length) {
// Access past the end of the string is intentional.
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
chr4 = input.charCodeAt(i++);
chr = ((chr1 << 24) | (chr2 << 16) | (chr3 << 8) | chr4) >>> 0;
enc1 = (chr / (85 * 85 * 85 * 85) | 0) % 85 + 33;
enc2 = (chr / (85 * 85 * 85) | 0) % 85 + 33;
enc3 = (chr / (85 * 85) | 0 ) % 85 + 33;
enc4 = (chr / 85 | 0) % 85 + 33;
enc5 = chr % 85 + 33;
output += String.fromCharCode(enc1) +
String.fromCharCode(enc2);
if (!isNaN(chr2)) {
output += String.fromCharCode(enc3);
if (!isNaN(chr3)) {
output += String.fromCharCode(enc4);
if (!isNaN(chr4)) {
output += String.fromCharCode(enc5);
}
}
}
}
output += "~>";
return output;
}
<input onKeyUp="result.innerHTML = encodeAscii85(this.value)" placeholder="write text here" type="text">
<p id="result"></p>
Here is matching ASCII85 AKA Base85 decoder (for user Qwerty) in JavaScript:
function decode_ascii85(a) {
var c, d, e, f, g, h = String, l = "length", w = 255, x = "charCodeAt", y = "slice", z = "replace";
for ("<~" === a[y](0, 2) && "~>" === a[y](-2), a = a[y](2, -2)[z](/\s/g, "")[z]("z", "!!!!!"),
c = "uuuuu"[y](a[l] % 5 || 5), a += c, e = [], f = 0, g = a[l]; g > f; f += 5) d = 52200625 * (a[x](f) - 33) + 614125 * (a[x](f + 1) - 33) + 7225 * (a[x](f + 2) - 33) + 85 * (a[x](f + 3) - 33) + (a[x](f + 4) - 33),
e.push(w & d >> 24, w & d >> 16, w & d >> 8, w & d);
return function(a, b) {
for (var c = b; c > 0; c--) a.pop();
}(e, c[l]), h.fromCharCode.apply(h, e);
}
<input onKeyUp="result.innerHTML = decode_ascii85(this.value)" placeholder="insert encoded string here" type="text">
<p id="result"></p>
example: <xmp><~<+oue+DGm>#3BW*D/a<&+EV19F<L~></xmp>

Formatting file sizes in Java/JSTL [duplicate]

This question already has answers here:
How can I convert byte size into a human-readable format in Java?
(31 answers)
Closed 8 years ago.
I was wondering if anyone knew of a good way to format files sizes in Java/JSP/JSTL pages.
Is there a util class that with do this?
I've searched commons but found nothing. Any custom tags?
Does a library already exist for this?
Ideally I'd like it to behave like the -h switch on Unix's ls command
34 -> 34
795 -> 795
2646 -> 2.6K
2705 -> 2.7K
4096 -> 4.0K
13588 -> 14K
28282471 -> 27M
28533748 -> 28M
A quick google search returned me this from Appache hadoop project. Copying from there:
(Apache License, Version 2.0):
private static DecimalFormat oneDecimal = new DecimalFormat("0.0");
/**
* Given an integer, return a string that is in an approximate, but human
* readable format.
* It uses the bases 'k', 'm', and 'g' for 1024, 1024**2, and 1024**3.
* #param number the number to format
* #return a human readable form of the integer
*/
public static String humanReadableInt(long number) {
long absNumber = Math.abs(number);
double result = number;
String suffix = "";
if (absNumber < 1024) {
// nothing
} else if (absNumber < 1024 * 1024) {
result = number / 1024.0;
suffix = "k";
} else if (absNumber < 1024 * 1024 * 1024) {
result = number / (1024.0 * 1024);
suffix = "m";
} else {
result = number / (1024.0 * 1024 * 1024);
suffix = "g";
}
return oneDecimal.format(result) + suffix;
}
It uses 1K = 1024, but you can adapt this if you prefer. You also need to handle the <1024 case with a different DecimalFormat.
You can use the commons-io FileUtils.byteCountToDisplaySize methods. For a JSTL implementation you can add the following taglib function while having commons-io on your classpath:
<function>
<name>fileSize</name>
<function-class>org.apache.commons.io.FileUtils</function-class>
<function-signature>String byteCountToDisplaySize(long)</function-signature>
</function>
Now in your JSP you can do:
<%# taglib uri="/WEB-INF/FileSizeFormatter.tld" prefix="sz"%>
Some Size: ${sz:fileSize(1024)} <!-- 1 K -->
Some Size: ${sz:fileSize(10485760)} <!-- 10 MB -->

Categories