Convert time to float and viceversa in Java - java

I need to show some times value on a linear chart and I built a snippet code to convert the values from time to float in Java.
My code doesn't works very well because I can't convert from float to time...
This is my result:
From time to float:
7:43 --> 7.7166667
From float to time:
7.7166667 --> 7:60 (this is wrong...I would to see 7:43)
This is my snippet code:
public class Test {
public static void main(String[] args)
{
String time = "7:43";
float timeFloat = Float.parseFloat(time.replace(":","."));
float resultTo100 = convertTo100(timeFloat);
System.out.println(resultTo100);
String resultTo60 = convertTo60(resultTo100);
System.out.println(resultTo60);
}
public static float convertTo100(float input)
{
String input_string = Float.toString(input);
BigDecimal inputBD = new BigDecimal(input_string);
String hhStr = input_string.split("\\.")[0];
BigDecimal output = new BigDecimal(Float.toString(Integer.parseInt(hhStr)));
output = output.add((inputBD.subtract(output).divide(BigDecimal.valueOf(60), 10, BigDecimal.ROUND_HALF_EVEN)).multiply(BigDecimal.valueOf(100)));
return Float.parseFloat(output.toString());
}
public static String convertTo60(float input)
{
String input_string = Float.toString(input);
BigDecimal inputBD = new BigDecimal(input_string);
String hhStr = input_string.split("\\.")[0];
BigDecimal output = new BigDecimal(Float.toString(Integer.parseInt(hhStr)));
output = output.add((inputBD.subtract(output).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_EVEN)).multiply(BigDecimal.valueOf(60)));
return output.toString().replace(".",":");
}
}
What am I doing wrong?
Thanks!

in your convertTo60 switch the order of divide and multiply operations.

Related

Java: convert floating point binary to floating point decimal

I want to convert a string representing the mantissa portion of a IEEE754 double.
Cannot find if there is such a conversion method in Java, in order to avoid manually adding 1 + 1/2 + 1/4 + 1/8 etc.
|0100000011001010000111110000000000000000000000000000000000000000 --> 13374 in IEEE754
|------------1010000111110000000000000000000000000000000000000000 --> mantissa part
| 1.1010000111110000000000000000000000000000000000000000 --> restoring fixed value 1
String s = "1.1010000111110000000000000000000000000000000000000000"
double mant10 = Double.readFromFloatBinary(s); // does such method exists in Java?
Yes, there are ways to read from a binary representation. But you don't have a representation in an IEEE format.
I would ignore the period and read as a BigInteger base2, then create a value to divide by also using BigInteger:
private static double binaryStringToDouble(String s) {
return stringToDouble(s, 2);
}
private static double stringToDouble(String s, int base) {
String withoutPeriod = s.replace(".", "");
double value = new BigInteger(withoutPeriod, base).doubleValue();
String binaryDivisor = "1" + s.split("\\.")[1].replace("1", "0");
double divisor = new BigInteger(binaryDivisor, base).doubleValue();
return value / divisor;
}
#Test
public void test_one_point_5() {
String s = "1.1";
double d = binaryStringToDouble(s);
assertEquals(1.5, d, 0.0001);
}
#Test
public void test_6_8125() {
String s = "110.1101";
double d = binaryStringToDouble(s);
assertEquals(6.8125, d, 0.0001);
}
#Test
public void test_yours() {
String s = "1.1010000111110000000000000000000000000000000000000000";
double d = binaryStringToDouble(s);
assertEquals(1.632568359375, d, 0.000000000000000001);
}
#Test
public void test_yours_no_trailing_zeros() {
String s = "1.101000011111";
double d = binaryStringToDouble(s);
assertEquals(1.632568359375, d, 0.000000000000000001);
}

Hexadecimal Calculations for Calculator [duplicate]

How to convert hexadecimal string to single precision floating point in Java?
For example, how to implement:
float f = HexStringToFloat("BF800000"); // f should now contain -1.0
I ask this because I have tried:
float f = (float)(-1.0);
String s = String.format("%08x", Float.floatToRawIntBits(f));
f = Float.intBitsToFloat(Integer.valueOf(s,16).intValue());
But I get the following exception:
java.lang.NumberFormatException: For input string: "bf800000"
public class Test {
public static void main (String[] args) {
String myString = "BF800000";
Long i = Long.parseLong(myString, 16);
Float f = Float.intBitsToFloat(i.intValue());
System.out.println(f);
System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
}
}
You need to convert the hex value to an int (left as an exercise) and then use Float.intBitsToFloat(int)

java : better way of doing this than using if and else

I have a requirement were depending on a particular key value of a map , i need to format the output .
For example if its value greater than 1 then needed to display only 2 decimal points after the value
(12.23) or else if its value is less than 1 , i need to show 4 decimal points after it .
I have written the code its working fine , but i am looking for a better way of doing this (basically i didn't liked if else conditions in my code )
This is my program where depending on the last attribute key value i am formatting the output
package com;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class CustValues {
public static void main(String args[]) {
Map valuesMap = new HashMap();
valuesMap.put("mktCap", "12.4d");
valuesMap.put("last", "0.4344");
valuesMap.put("avgvalue", "34.55");
valuesMap.put("bidprice", "44.44");
Iterator<String> iterator = valuesMap.keySet().iterator();
while (iterator.hasNext()) {
String name = iterator.next().toString();
String value = (String) valuesMap.get(name);
if (name.equals("last")) {
String result = "";
double d = Double.parseDouble(value);
if (d > 1) {
result = formatNumber(value, 2);
} else {
result = formatNumber(value, 4);
}
System.out.println(result);
}
}
}
public static String formatNumber(String s, int decPts) {
double d = Double.parseDouble(s);
if (2 == decPts)
return new DecimalFormat("#,###,###,##0.00").format(d);
else if (0 == decPts)
return new DecimalFormat("#,###,###,##0").format(d);
else if (3 == decPts)
return new DecimalFormat("#,###,###,##0.000").format(d);
else if (4 == decPts)
return new DecimalFormat("0.0000").format(d);
return String.valueOf(d);
}
}
You could create a Map<Integer, DecimalFormat> formats (or a List<DecimalFormat>, if you prefer). Then formatNumber() simply calls formats.get(decPts) to get the correct format.
The logic you're implementing in the formatNumber method is the perfect candidate for a switch statement. Try
switch (decPts) {
case 0:
return new DecimalFormat("#,###,###,##0").format(d);
break;
case 2:
return new DecimalFormat("#,###,###,##0.00").format(d);
break;
...
}
For more info see this tutorial.
edit: Although SJuan76 beat me to it, and I like Code-Guru's idea better!
Building on Code-Guru's answer. You can use a map but to retain the same thread safety and default behavior the code becomes:
public class CustValues {
private static final Map<Integer, String> FORMATS;
static {
Map<Integer, String> formats = new HashMap<Integer, String>();
formats.put( 0, "#,###,###,##0" );
formats.put( 2, "#,###,###,##0.00" );
formats.put( 3, "#,###,###,##0.000" );
formats.put( 4, "0.0000" );
FORMATS = Collections.unmodifiableMap( formats );
}
public static void main(String args[]) {
// Same as before....
}
public static String formatNumber(String s, int decPts) {
double d = Double.parseDouble(s);
String format = FORMATS.get(decPts);
if( format != null ) {
return new DecimalFormat(format).format(d);
}
return String.valueOf(d);
}
}
You need to create a new DecimalFormat for each request instead of reusing it since it is not thread safe. This also handles the cases where decPts is not 0, 2, 3, or 4.
I have method as below:
public static String formatNumber(String s, int decPts) {
double d = Double.parseDouble(s);
if (decPts >= 0 && decPts <= 4) {
DecimalFormat df = new DecimalFormat("###,##0");
df.setMaximumFractionDigits(decPts);
df.setMinimumFractionDigits(decPts);
return df.format(d);
}
return String.valueOf(d);
}
You can use the switch sentence
switch (decPts) {
case 0:
return new DecimalFormat("#,###,###,##0").format(d);
case 2:
...
}
It helps tidy the code for this case. Anyway you would not be able to program in any language without using ìf or similar constructs.
Enums have the advantage of avoiding boxing and unboxing an integer that a map.get call would perform, while only creating the formatters you need one time. Note, you can also could get rid of the second double parse:
enum DisplayFormat {
CURRENCY(new DecimalFormat("#,###,###,#00.00")),
SMALL_CURRENCY(new DecimalFormat("0.000"));
private DecimalFormat f;
public DisplayFormat(DecimalFormat f) {
this.f = f;
}
public String format(double d) {
return this.f.format(d);
}
// Usage:
if (name.equals("last")) {
String result = "";
double d = Double.parseDouble(value);
if (d > 1) {
result = DisplayFormat.SMALL_CURRENCY.format(d)
} else {
result = DisplayFormat.CURRENCY.format(d)
}
System.out.println(result);
}
One really inefficient, but more flexible option would be to generate the format string based on decPts:
public static String formatNumber(String s, int decPts) {
double d = Double.parseDouble(s);
final String baseFormat = "#,###,###,##0";
// TODO: Use a StringBuilder
String format = decPts==0 ? baseFormat : baseFormat + ".";
for (int i=0; i < decPts; i++) {
format += "0";
}
return new DecimalFormat(format).format(d);
}
Again, this is a bad idea unless you need to show an arbitrary number of decimal points or can only determine the way to display the number at run-time, which probably isn't the case.

How to use String.format to convert a long to a String in currency format in Java

I need to learn how to convert a long value into a currency formatted string in a toString() method with the following scenarios:
If given long value = 9287, needs to be displayed as $92.87
If given long value = -9287, needs to be displayed as $-92.87
If given long value = 100000000, needs to be displayed as $1,000,000.00
If given long value = 49, needs to be displayed as $0.49
Any help from string gurus is appreciated.
public static void main(String [] args){
DecimalFormat f = new DecimalFormat("$#,##0.00;-$#,##0.00");
//test with
long num1 = 9287;
long num2 = -9287;
long num3 = 100000000;
long num4 = 49;
System.out.println("num1 = "+f.format(num1/100.0));
System.out.println("num2 = "+f.format(num2/100.0));
System.out.println("num3 = "+f.format(num3/100.0));
System.out.println("num4 = "+f.format(num4/100.0));
}
I hope you're using Java. Try this :
import java.text.NumberFormat;
NumberFormat f = NumberFormat.getCurrencyInstance();
System.out.println(f.format(doubleValue(yourVar)/100));
String.format() does not support currency format. So you need to insert currency symbol yourself or use java.text package.
package tests;
import java.util.Locale;
public class App201210130101 {
/**
* #param args
*/
public static void main(String[] args) {
long value;
value = 9287;
print(value);
value = -9287;
print(value);
value = 100000000;
print(value);
value = 49;
print(value);
}
public static void print(long value) {
System.out.println(String.format(Locale.US, "$%,.2f", (double)value/100));
}
}

How to convert hex string to float in Java?

How to convert hexadecimal string to single precision floating point in Java?
For example, how to implement:
float f = HexStringToFloat("BF800000"); // f should now contain -1.0
I ask this because I have tried:
float f = (float)(-1.0);
String s = String.format("%08x", Float.floatToRawIntBits(f));
f = Float.intBitsToFloat(Integer.valueOf(s,16).intValue());
But I get the following exception:
java.lang.NumberFormatException: For input string: "bf800000"
public class Test {
public static void main (String[] args) {
String myString = "BF800000";
Long i = Long.parseLong(myString, 16);
Float f = Float.intBitsToFloat(i.intValue());
System.out.println(f);
System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
}
}
You need to convert the hex value to an int (left as an exercise) and then use Float.intBitsToFloat(int)

Categories