Convert string 2 decimal places in Java - java

In Java, I am trying to parse a string of format "0.##" to a float. The string should always have 2 decimal places.
public ArrayList getFixRateDetails (String merchantccy,String paymodetype,String amount)
{
String returnAmt ="";
ArrayList list= new ArrayList();
float value=-1;
try {
NiCurrencyConverterProcessor nicc= new NiCurrencyConverterProcessor();
list=nicc.getFixRateDetails(merchantccy,paymodetype);
Float i = (Float.parseFloat((String) list.get(0)));
Float j = (Float.parseFloat(amount));
value=i*j;
list.set(0, value);
list.add(2, i);
GenericExceptionLog.log("PayPalUtility.java : In getFixRateDetails() : value:"+list,"paymenttarasectionsevlet111");
DecimalFormat df = new DecimalFormat("0.00");
String ReturnAmt = df.format(returnAmt);
returnAmt=String.valueOf(value).trim();
GenericExceptionLog.log("PayPalUtility.java : In getFixRateDetails() : value:"+returnAmt,"paymenttarasectionsevlet222");
} catch (Throwable t) {
GenericAsyncLogger.Logger(t,"ERROR","DB","Transaction","MIGSTxnUtility.java","postingAmtConversion()","NA","NA","","","paymenttarasectionsevlet");
//GenericExceptionLog.exceptionJava(t,"postingAmtConversion()", "MIGSTxnUtility");
}
return list;
}
}

You are assigning the formatted output to the different variable (ReturnAmt) and in the log you are printing returnAmt. It is obvious that it will print the value without formatting.
Try
DecimalFormat formatter = new DecimalFormat("0.00");
returnAmt = formatter.format(value);
For more information refer DecimalFormat
Example:
public static void main(String...args){
String returnAmt ="";
Float i = 100f;
Float j = 200f;
Float value=i*j;
DecimalFormat formatter = new DecimalFormat("0.00");
returnAmt = formatter.format(value);
System.out.println(returnAmt);
}
OUTPUT:
20000.00

Related

Java floating point number in comma instead of dot

All I have a floating point number in Finnish local. It is like the following:-
String numberString = "1000,30";
if(numberString.contains(",")){
numberString = numberString.replaceAll(",",".").trim();
}
try {
Number number = Double.parseDouble(numberString);
return number;
}catch (NumberFormatException ex){
System.out.printf(ex.getMessage());
}
return null;
But this number has value 1000.30. I would like the number should I have value 1000,30. How can I have Number with the comma instead of the dot?
This is a basic question it must have been asked earlier. But all I find is in String data type. I don't see any Number data type.
When seeing your comment that the API accepts only Number and that it calls Number#toString() on it, then I see only 1 way to enforce the rightful display. By using your own implementation of Number and overwriting the way Object#toString() works:
public class CorrectlyDisplayedDouble extends Number{
private final Double internal;
public CorrectlyDisplayedDouble(Double internal){
this.internal = internal;
}
public int intValue(){
return internal.intValue();
}
public long longValue(){
return internal.longValue();
}
public float floatValue(){
return internal.floatValue();
}
public double doubleValue(){
return internal.doubleValue();
}
public String toString(){
// replaces periods with commas
return internal.toString().replace(".", ",");
}
}
Which can then be easily created using following snippet, which then also can be passed to your third party API:
Number number = new CorrectlyDisplayedDouble(Double.parseDouble(numberString));
Sample Code :
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
This will help you to understand how Locale exactly works:
public double parse(String decimalAsText) {
NumberFormat decimalFormat = NumberFormat.getNumberInstance(Locale.FRANCE);
decimalAsText = decimalAsText.replace(' ', '\u00a0');
ParsePosition pp = new ParsePosition(0);
Number n = decimalFormat.parse(decimalAsText, pp);
return n.doubleValue();
}
public String parse(double textAsDecimal) {
NumberFormat nf = NumberFormat.getNumberInstance(Locale.FRENCH);
BigDecimal bd = BigDecimal.valueOf(textAsDecimal);
nf.setMaximumFractionDigits(bd.scale());
String s = nf.format(textAsDecimal);
return s;
}
You can use DecimalFormat and Locale, for example:
DecimalFormat dfFrance = (DecimalFormat)DecimalFormat.getInstance(Locale.FRANCE);
dfFrance.applyPattern("###.00");
Number n = 0;
try {
n = dfFrance.parse("1000,30");
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(n.doubleValue());

How to get Random numbers to test math equation?

I have trouble with this equation: E * cotangent((q * E)/(k * t)) = nkT/q.
I'm looking for the values of E for the equality can be achieved
knowing that: q and k are constants, t and n are variables.
For that I tried this code but apparently is failed:
public class Equation {
public static double q = 1.6E-19;
public static double k = 1.38E-23;
//double y = E * 1/Math.tan(E*q/k*t);
//DecimalFormat df = new DecimalFormat("#.#####");
public static double[] nktq = new double[]{0.02857,0.02674,0.03118,0.02829,0.02976,0.02898,0.03001,0.02953,0.032};
public static double[] t = new double[]{80,100,150,200,250,280,300,320,350};
public static double[] n = new double[]{4.14,3.1,2.41,1.64,1.38,1.20,1.16,1.07,1.06};
private static DecimalFormat df2 = new DecimalFormat(".##");
public static double genE(){
double start = 0;
double end = 30;
double random = new Random().nextDouble();
// DecimalFormat df = new DecimalFormat("#.##");
// df.setRoundingMode(RoundingMode.FLOOR);
double E = start + (random * (end - start));
//double E = new Double(df.format(result));
System.out.println(df2.format(E));
return E;
}
public static void main(String[] args) {
//double y = E * 1/Math.tan(E*q/k*t);
//DecimalFormat df = new DecimalFormat("#.#####")
double E = 0;
while ( Math.round(E * 1/Math.tan((q * E)/(k * t[0]))*100000)!= nktq[0]){
genE();
}
}
}
Any help is appreciated!
You create a new Random instance for each value. That's wrong.
Here's what I'd recommend you try:
public class Equation {
private Random random;
public Equation() { this(null); }
public Equation(Long seed) {
this.random = (seed == null) ? new Random() : new Random(seed.longValue());
}
public double nextConst() { return this.random.nextDouble(); }
public double nextConst(double start, double end) {
return start + (end-start)*this.random.nextDouble();
}
// Add the rest of your stuff here.
}

Convert time to float and viceversa in 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.

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.

need to get original double data from NumberFormatted double

I need percentage form of a double value, so I used NumberFormat
double d = 0.13;
NumberFormat nf = NumberFormat.getPercentInstance();
String kpr = nf.format(kpr);
I saved this property to an object Person through setter. When I get it back through getter method it returns String(of course).
Is there a way to de-format this String to double value as 0.13, so that I can perform arithmetics on it?
public static void main(String s[]) {
getDoubleFromStringWithPercent("12345%");
}
private static Double getDoubleFromStringWithPercent(String string) {
Locale locale = Locale.CANADA;
Double num = null;
try {
Number number = NumberFormat.getPercentInstance(locale).parse(string);
if (number instanceof Long) {
num = ((Long) number).doubleValue();
} else {
num = (Double) number;
}
} catch (ParseException e) {
throw new RuntimeException(e);
}
return num;
}
Locale need for find decimal delimiter ("." or ",");
Alternative version:
String string ="2165%";
double d = Double.parseDouble(string.substring(0, string.length()-1));
if (d != 0) {
d = d / 100;
}
double d=(Double.parase(kpr.substring(kpr.length-1)))/100;

Categories