Can someone help me getting the exact value to BigDecimal?
My code is as below,
import java.math.BigDecimal;
public class HelloWorld{
public static void main(String []args){
String x="2.7955814565E10";
BigDecimal y=new BigDecimal(x);
System.out.println(y.toPlainString());
}
}
My actual value in the DB is 27955814565.0, a String. I read this string from DB and set it in a bean class where the amt field has type string, using the value "2.7955814565E10". When I try to convert this to a BigDecimal I get 27955814565 instead of 27955814565.0.
Can someone tell me what is the issue because for rest all fields the logic for converting the string value to BigDecimal is working fine and I want the exact value as in DB?
The BigDecimal doesn't infer extra digits in this case.
If the input is
String x = "2.79558145650E10"; // note the extra 0
you get the expected result. You can also add the digit as required.
String x = "2.7955814565E10";
BigDecimal y = new BigDecimal(x);
if (y.scale() < 1)
y = y.setScale(1);
System.out.println(y.toPlainString());
prints
27955814565.0
BTW If your input is
String x = "2.7955814565000E10"; // note the extra 000
the output is
27955814565.000
As you already know, Your String is in scientific notation,
To translate these value into origional BigDecimal or Decimal we need a proper way.
public class Test {
public static void main(String[] args) {
double firstNumber = 12345678;
double secondNumber = 0.000012345678;
String firstNumberAsString = String.format ("%.0f", firstNumber);
String secondNumberAsString = String.format("%.12f",secondNumber);
System.out.println(firstNumberAsString);
System.out.println(secondNumberAsString);
}
}
output will be:
12345678
0.000012345678
You can use Format method as well on BigDecimal to achieve your goal.
DecimalFormat decimalFormat = new DecimalFormat("0.0000000000");
Related
I have the following code where I need to print value up to two decimal places removing the dot(.) from the number.
How ever sometimes it print up to two and sometimes up to three places off decimal.
public class CheckSubString3 {
public static void main(String[] args) {
Double[] d={134344.00d,234434.08d,234434.02d};
for(int i=0; i<d.length; i++){
System.out.println((d[i])*(25)/100);
System.out.println(parseLonggetFormattedAmount((d[i])*(25)/100));
System.out.println();
}
}
private static String parseLonggetFormattedAmount(double d) {
DecimalFormat format = (DecimalFormat) NumberFormat
.getInstance(new Locale("en", "gb"));
format.setMinimumFractionDigits(2);
FieldPosition f = new FieldPosition(0);
StringBuffer s = new StringBuffer();
String value = format.format(d, s, f).toString().replace(',', ' ')
.replace('.', ' ');
return value.replaceAll(" ","");
}
}
Below is the output:
original value 33586.0
required value 3358600
original value 58608.52
required value 5860852
original value 58608.505
required value 58608505// This line is giving upto 3 places of decimal
According to the NumberFormat documentation, you could use setMaximumFractionDigits(int newValue)
Sets the maximum number of digits allowed in the fraction portion of a number.
just put it in your function parseLonggetFormattedAmount(double d):
format.setMaximumFractionDigits(2);
It seems you simply want to multiply the doubles by 100 and round to the nearest integer. So your method could be written:
private static String parseLonggetFormattedAmount(double d) {
return String.valueOf(Math.round(d * 100));
}
Which outputs:
3358600
5860852
5860851
I need to print a Double as a String but I don't know how many decimal places there will be and I have to be prepared for as many as possible. Right, now I'm using this ugly solution:
Double dubs = 0.000157;
NumberFormat formatter = new DecimalFormat(
"##.########################################################################################");
System.out.println(formatter.format(dubs));
You can do this with no conversion:
public class codesnippets {
public static void main(String[] args)
{
Double dubs = 0.000157;
System.out.printf("%f", dubs);
}
}
You can also use
Double dubs = 0.000157;
String dubs_format = String.format("%f", dubs);
System.out.println(dubs);
EDIT: Apparently there is a precision loss when using "%f" as a format string. If this is the case for you, use "%.10f"
Try here man. I think this is what you're saying. The answer given at the bottom.
Number of decimal digits in a double
Here is what I meant.
double d= 234.12413;
String text = Double.toString(Math.abs(d));
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;
Then you just concatenate them
String xmlString = integerPlaces.toString() + "." + decimalPlaces.toString();
This seemed to work based on Steampunkery's idea. The catch was that I needed an actual String which I realize I wasn't clear on.
String dubString= String.format("%f", dubs);
System.out.println(dubString);
I'm attempting to get a user input of a decimal, then round it to two decimal points. This is the code I currently have which is not working correctly, and I'm not sure why.
package code;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class DecimalPlaces {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
Scanner qweInput = new Scanner(System.in);
System.out.println("Enter a decimal number:");
String qwe1 = qweInput.next();
df.format(qwe1);
System.out.println(qwe1);
}
}
With scanner, better use nextLine() when you can do it, it preserves from errors with the return line char:
String qwe1 = qweInput.nextLine();
Then you need to parse to double, because if not it tries to cast from Object to double and it crashes
df.format(Double.parseDouble(qwe1));
Then the format method return the string formated, because String are immutable, so you need to print direclty or save it :
qwe1 = df.format(Double.parseDouble(qwe1));
System.out.println(qwe1);
//----------------------------------OR----------------------------------
System.out.println(df.format(Double.parseDouble(qwe1)));
Edit : to avoid parsing to Double you can use nextDouble() from Scanner, as it it would direclty save as a double, but to save the format you would need another String so, with proper name ;)
Instead of
String qwe1 = qweInput.next();
try
double qwe1 = qweInput.nextDouble();
By the way, qwe1 is a terrible name for a variable! Variable names should reflect what they are for.
I would suggest getting the user input as a double and then do this:
double roundNum = Math.round(num * 100.0) / 100.0;
I have read many posts in this forum on converting user input to 2 decimal place.
However, I am required to write a method on its own and only be responsible for converting user input to 2 decimal places.
I am currently meeting an error of not being able to convert String to double when doing the decimal conversion.
Below is my current code.
public class LabQuestion
{
static double twoDecimalPlace (double usrInput){
DecimalFormat twoDpFormat = new DecimalFormat("#.##");
usrInput=twoDpFormat.format(usrInput);
return usrInput;
}
public static void main(String[] args)
{
System.out.print("Enter a number on a line: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
twoDecimalPlace("Current input ",d);
}
}
How may I be able to create a method that allows converting to 2 decimal place of a double input from user? Thank you.
You use a NumberFormat object such as a DecimalFormat object to convert a String to a number, which is called "parsing" the String or a number to a String, which is called "formatting" the number, and so you will need to decide which it is you would like to do with this method. It sounds like you want to change the display of the number to show a String representation with 2 decimal places, and so I think that your output should be a String. For example:
import java.text.DecimalFormat;
import java.util.Scanner;
public class NumberFormater {
static DecimalFormat twoDpFormat = new DecimalFormat("#0.00");
static String twoDecimalPlace(double usrInput) {
String output = twoDpFormat.format(usrInput);
return output;
}
public static void main(String[] args) {
System.out.print("Enter a number on a line: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
System.out.println("Output: " + twoDecimalPlace(d));
}
}
Try this:
public Double formatDouble(Number number){
return Double.parseDouble(String.format("%.3f", "" + number));
}
I have a string whose value will be like '1/3' or '1/2'. It can be even '2/3'. I need to convert it into its equivalent percentage value upto 2 decimal places and again convert it into String.
Is there any java API already present which does it automatically?
Please let me know if you know any optimum solution for this.
below code might resolve this:
import java.util.StringTokenizer;
public class percentage {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String x="2/3";
System.out.println(convert(x));
}
public static String convert(String x){
int num=0;
StringTokenizer s= new StringTokenizer(x, "/");
while(s.hasMoreElements()){
num =Integer.parseInt(s.nextToken())/Integer.parseInt(s.nextToken());
}
return num+"";
}
}
I have wrote a method of my own to resolve this. convert() method would return a String which gives the desirable output.
To convert a double to a percentage String you can use:
double number = ...;
NumberFormat numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMaximumFractionDigits(2);
String formattedString = numberFormat.format(number);
You could create your own method simply splitting string by "/" and then parsing the strings(of array) numerator and denominator into double.