I'm trying to read some BigDecimal values from the string. Let's say I have this String: "1,000,000,000.999999999999999" and I want to get a BigDecimal out of it. What is the way to do it?
First of all, I don't like the solutions using string replaces (replacing commas etc.). I think there should be some neat formatter to do that job for me.
I've found a DecimalFormatter class, however as it operates through double - huge amounts of precision are lost.
So, how can I do it?
Check out setParseBigDecimal in DecimalFormat. With this setter, parse will return a BigDecimal for you.
String value = "1,000,000,000.999999999999999";
BigDecimal money = new BigDecimal(value.replaceAll(",", ""));
System.out.println(money);
Full code to prove that no NumberFormatException is thrown:
import java.math.BigDecimal;
public class Tester {
public static void main(String[] args) {
// TODO Auto-generated method stub
String value = "1,000,000,000.999999999999999";
BigDecimal money = new BigDecimal(value.replaceAll(",", ""));
System.out.println(money);
}
}
Output
1000000000.999999999999999
The following sample code works well (locale need to be obtained dynamically)
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.Locale;
class TestBigDecimal {
public static void main(String[] args) {
String str = "0,00";
Locale in_ID = new Locale("in","ID");
//Locale in_ID = new Locale("en","US");
DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance(in_ID);
nf.setParseBigDecimal(true);
BigDecimal bd = (BigDecimal)nf.parse(str, new ParsePosition(0));
System.out.println("bd value : " + bd);
}
}
The code could be cleaner, but this seems to do the trick for different locales.
import java.math.BigDecimal;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class Main
{
public static void main(String[] args)
{
final BigDecimal numberA;
final BigDecimal numberB;
numberA = stringToBigDecimal("1,000,000,000.999999999999999", Locale.CANADA);
numberB = stringToBigDecimal("1.000.000.000,999999999999999", Locale.GERMANY);
System.out.println(numberA);
System.out.println(numberB);
}
private static BigDecimal stringToBigDecimal(final String formattedString,
final Locale locale)
{
final DecimalFormatSymbols symbols;
final char groupSeparatorChar;
final String groupSeparator;
final char decimalSeparatorChar;
final String decimalSeparator;
String fixedString;
final BigDecimal number;
symbols = new DecimalFormatSymbols(locale);
groupSeparatorChar = symbols.getGroupingSeparator();
decimalSeparatorChar = symbols.getDecimalSeparator();
if(groupSeparatorChar == '.')
{
groupSeparator = "\\" + groupSeparatorChar;
}
else
{
groupSeparator = Character.toString(groupSeparatorChar);
}
if(decimalSeparatorChar == '.')
{
decimalSeparator = "\\" + decimalSeparatorChar;
}
else
{
decimalSeparator = Character.toString(decimalSeparatorChar);
}
fixedString = formattedString.replaceAll(groupSeparator , "");
fixedString = fixedString.replaceAll(decimalSeparator , ".");
number = new BigDecimal(fixedString);
return (number);
}
}
I needed a solution to convert a String to a BigDecimal without knowing the locale and being locale-independent. I couldn't find any standard solution for this problem so i wrote my own helper method. May be it helps anybody else too:
Update: Warning! This helper method works only for decimal numbers, so numbers which always have a decimal point! Otherwise the helper method could deliver a wrong result for numbers between 1000 and 999999 (plus/minus). Thanks to bezmax for his great input!
static final String EMPTY = "";
static final String POINT = '.';
static final String COMMA = ',';
static final String POINT_AS_STRING = ".";
static final String COMMA_AS_STRING = ",";
/**
* Converts a String to a BigDecimal.
* if there is more than 1 '.', the points are interpreted as thousand-separator and will be removed for conversion
* if there is more than 1 ',', the commas are interpreted as thousand-separator and will be removed for conversion
* the last '.' or ',' will be interpreted as the separator for the decimal places
* () or - in front or in the end will be interpreted as negative number
*
* #param value
* #return The BigDecimal expression of the given string
*/
public static BigDecimal toBigDecimal(final String value) {
if (value != null){
boolean negativeNumber = false;
if (value.containts("(") && value.contains(")"))
negativeNumber = true;
if (value.endsWith("-") || value.startsWith("-"))
negativeNumber = true;
String parsedValue = value.replaceAll("[^0-9\\,\\.]", EMPTY);
if (negativeNumber)
parsedValue = "-" + parsedValue;
int lastPointPosition = parsedValue.lastIndexOf(POINT);
int lastCommaPosition = parsedValue.lastIndexOf(COMMA);
//handle '1423' case, just a simple number
if (lastPointPosition == -1 && lastCommaPosition == -1)
return new BigDecimal(parsedValue);
//handle '45.3' and '4.550.000' case, only points are in the given String
if (lastPointPosition > -1 && lastCommaPosition == -1){
int firstPointPosition = parsedValue.indexOf(POINT);
if (firstPointPosition != lastPointPosition)
return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY));
else
return new BigDecimal(parsedValue);
}
//handle '45,3' and '4,550,000' case, only commas are in the given String
if (lastPointPosition == -1 && lastCommaPosition > -1){
int firstCommaPosition = parsedValue.indexOf(COMMA);
if (firstCommaPosition != lastCommaPosition)
return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY));
else
return new BigDecimal(parsedValue.replace(COMMA, POINT));
}
//handle '2.345,04' case, points are in front of commas
if (lastPointPosition < lastCommaPosition){
parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY);
return new BigDecimal(parsedValue.replace(COMMA, POINT));
}
//handle '2,345.04' case, commas are in front of points
if (lastCommaPosition < lastPointPosition){
parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY);
return new BigDecimal(parsedValue);
}
throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal.");
}
return null;
}
Of course i've tested the method:
#Test(dataProvider = "testBigDecimals")
public void toBigDecimal_defaultLocaleTest(String stringValue, BigDecimal bigDecimalValue){
BigDecimal convertedBigDecimal = DecimalHelper.toBigDecimal(stringValue);
Assert.assertEquals(convertedBigDecimal, bigDecimalValue);
}
#DataProvider(name = "testBigDecimals")
public static Object[][] bigDecimalConvertionTestValues() {
return new Object[][] {
{"5", new BigDecimal(5)},
{"5,3", new BigDecimal("5.3")},
{"5.3", new BigDecimal("5.3")},
{"5.000,3", new BigDecimal("5000.3")},
{"5.000.000,3", new BigDecimal("5000000.3")},
{"5.000.000", new BigDecimal("5000000")},
{"5,000.3", new BigDecimal("5000.3")},
{"5,000,000.3", new BigDecimal("5000000.3")},
{"5,000,000", new BigDecimal("5000000")},
{"+5", new BigDecimal("5")},
{"+5,3", new BigDecimal("5.3")},
{"+5.3", new BigDecimal("5.3")},
{"+5.000,3", new BigDecimal("5000.3")},
{"+5.000.000,3", new BigDecimal("5000000.3")},
{"+5.000.000", new BigDecimal("5000000")},
{"+5,000.3", new BigDecimal("5000.3")},
{"+5,000,000.3", new BigDecimal("5000000.3")},
{"+5,000,000", new BigDecimal("5000000")},
{"-5", new BigDecimal("-5")},
{"-5,3", new BigDecimal("-5.3")},
{"-5.3", new BigDecimal("-5.3")},
{"-5.000,3", new BigDecimal("-5000.3")},
{"-5.000.000,3", new BigDecimal("-5000000.3")},
{"-5.000.000", new BigDecimal("-5000000")},
{"-5,000.3", new BigDecimal("-5000.3")},
{"-5,000,000.3", new BigDecimal("-5000000.3")},
{"-5,000,000", new BigDecimal("-5000000")},
{null, null}
};
}
Here is how I would do it:
public String cleanDecimalString(String input, boolean americanFormat) {
if (americanFormat)
return input.replaceAll(",", "");
else
return input.replaceAll(".", "");
}
Obviously, if this were going in production code, it wouldn't be that simple.
I see no issue with simply removing the commas from the String.
resultString = subjectString.replaceAll("[^.\\d]", "");
will remove all characters except digits and the dot from your string.
To make it locale-aware, you might want to use getDecimalSeparator() from java.text.DecimalFormatSymbols. I don't know Java, but it might look like this:
sep = getDecimalSeparator()
resultString = subjectString.replaceAll("[^"+sep+"\\d]", "");
Old topic but maybe the easiest is to use Apache commons NumberUtils which has a method createBigDecimal (String value)....
I guess (hope) it takes locales into account or else it would be rather useless.
Please try this its working for me
BigDecimal bd ;
String value = "2000.00";
bd = new BigDecimal(value);
BigDecimal currency = bd;
Related
I have the following problem:
I have big values stored in the String, and I can only display number that is 7 digit long. Here are the examples after converting from string to float -
I have String 300 which should be 300, but it is 300.0
Everything that's bigger than 7 digits should be written in scientific notation (700000000 should be 7E+8)
It also could be 7.0E8, but I prefer 7E+8.
I have tried formatting the string but when I wasn't able to get rid of .0 without getting rid of scientific notation. Is this even possible ?
The class DecimalFormat from the package java.text handles this almost effortlessly. A tad bit of business logic for your specific case seals the deal.
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class NumberFormatter
{
public static void main(String args[])
{
String stringInput = "1234.5678";
String outputString = null;
if (stringInput.length() < 8)
{
outputString = stringInput;
}
else
{
outputString = scientificOutput(stringInput);
}
System.out.println(outputString);
}
private String scientificOutput(String input)
{
NumberFormat formatter = new DecimalFormat("0.###E0");
Double d = Double.parseDouble(input);
if (d % 1 == 0)
{
// is int
return formatter.format(d.intValue());
}
else
{
// is a double
return formatter.format(d);
}
}
}
Try this:
String inputValue = "700000000";
String result;
DecimalFormat df1 = new DecimalFormat("#######");
df1.setMinimumFractionDigits(0);
DecimalFormat df2 = new DecimalFormat("######E0");
df2.setMinimumFractionDigits(1);
if (inputValue.length() <= 7) {
result = df1.format(Double.parseDouble(inputValue));
} else {
result = df2.format(Double.parseDouble(inputValue));
}
I am trying to write a program that converts binary(with or without fraction) inputs into hex which is nearly done but unfortunately in the hex output the point (".")is missing.
Suppose my expected output is e7.6 , but i am getting e76 instead.
only the "." is missing.
here is my BinToHex class..
import java.io.*;
//tried to convert the binary into dec and then dec to hex
public class BinToHex {
double tempDec,fractionpart;
long longofintpart,templongDec;
String inpu ="11100111.011";
String hexOutput=null,tempDecString,hex = null;
static int i = 1;
public void convertbintohex() {
if (inpu.contains(".")) {
int placesAfterPoint = inpu.length() - inpu.indexOf(".") - 1;//every thing
long numerator = Long.parseLong(inpu.replace(".", ""), 2);//goes
double decimalOfInput = ((double) numerator) / (1L << placesAfterPoint);//alright till here
while (true) {
tempDec = decimalOfInput * 16;
if (tempDec == (int)tempDec) {
tempDecString = String.valueOf((long)tempDec);
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(templongDec);
break;
} else {
longofintpart = (long)tempDec;
hex=Long.toHexString(longofintpart);
if(i==1){
hexOutput = hex + ".";
i=i+1;
}else{
hexOutput = hexOutput + hex;
}
fractionpart = tempDec-(int)tempDec;
decimalOfInput = fractionpart;
}
}
} else {
// this part is ok
tempDecString = String.valueOf(Integer.parseInt(inpu, 2));
templongDec = Long.parseLong(tempDecString, 10);
hexOutput = Long.toHexString(templongDec);
}
System.out.println(hexOutput);
}
}
my main Test class..
public class Test{
public static void main(String args[]){
BinToHex i = new BinToHex();
i.convertbintohex();
}
}
I am stuck!
plz help .
really, not i can't resist to write a solution... after having such long comments, it jst takes me some minutes ^^
final int CODEBASE = 16;
String input = "11100111.011";
//lets see if we have a '.' in our String
if (input.indexOf(".") > 0) {
//yes, we have one - so we can split the string by '.'
String splits = input.split(".");
//the part left of the dot
String beforeDot = splits[0];
//the part right of the dot
String afterDot = splits[1];
//it's a incomplete input, we must fill up with
//trailing zeros according to out code base
afterDot.fillTrailingZeros(afterDot, CODEBASE);
//now we can parse the input
int asIntBefore = Integer.parseInt(beforeDots, 2);
int asIntAfter = Integer.parseInt(afterDot , 2);
} else {
//use your working code for
//input wthoput dot HERE
}
//fills trailing zeros to input String
String fillTrailingZeros(String input, int base){
//as long as our String is shorter than the codebase...
while (input.length() < base){
//...we have to add trailing zeros
input = input +"0";
}
return input;
}
At last found a proper algorithm for converting decimal(with or without fraction) to hex.
besides, binary(with or without fraction) to decimal in Java is here
The algorithm for converting decimal(with or without fraction) into hex in Java
import java.math.*;
public class DecimalToHex{
public String decimalToHex(String decInpString){
StringBuilder hexOut = new StringBuilder();
double doubleOfDecInp = Double.parseDouble(decInpString);
if(doubleOfDecInp < 0){
hexOut = hexOut.append("-");
doubleOfDecInp = -doubleOfDecInp;
}
BigInteger beforedot = new BigDecimal(doubleOfDecInp).toBigInteger();
hexOut.append(beforedot.toString(16));
BigDecimal bfd =new BigDecimal(beforedot);
doubleOfDecInp = doubleOfDecInp - bfd.doubleValue();
if(doubleOfDecInp == 0){
return hexOut.toString();
}
hexOut.append(".");
for (int i = 0; i < 16; ++i) {
doubleOfDecInp = doubleOfDecInp * 16;
int digit = (int)doubleOfDecInp;
hexOut.append(Integer.toHexString(digit));
doubleOfDecInp = doubleOfDecInp - digit;
if (doubleOfDecInp == 0)
break;
}
return hexOut.toString();
}
public static void main(String args[]){
String decimalInp = "-0.767";
String out ;
DecimalToHex i = new DecimalToHex();
out = i.decimalToHex(decimalInp);
System.out.println(out);
}
}
I have to write a program to convert between linear units in, ft, mi, mm, cm, m, km. I know there are easier and better ways to do this. I think we'ere just trying to fully understand if else if statements. But this is what I have so far. I'm just trying to figure out if I am on the right track. I've tried to write out some pseudocode but it just seems like a lot going on so I find it a bit overwhelming. Next I'm going to add a method to convert form in or mm to whatever is selected by the user.
When I test the program i get this: UnitConversion#76c5a2f7 (EDIT: THIS ISSUE WAS FIXED)
Ok I made the suggested changes and that allowed the first part of the program to run properly. I have now added my second method to convert from in/mm to the other measurements.. I was having issues but I figured it out.
Here is my main method;
public class LinearConversion
{
public static void main(String[] args)
{
UnitConversion newConvert = new UnitConversion("km", "m", 100);
System.out.println(newConvert);
}
}
Any suggestions? What am I missing or not understanding about doing this sort of program?
public class UnitConversion
{
private String input;
private String output;
private double value;
private double temp;
private double in, ft, mi, mm, cm, m, km;
private final double inch_feet = 12;
private final double inch_miles = 63360;
private final double inch_millimeters = 25.4;
private final double inch_centimeters = 2.54;
private final double inch_meters = 0.0254;
private final double inch_kilometers = 0.0000254;
private final double millimeters_inch = 0.0393701;
private final double millimeters_feet = 0.00328084;
private final double millimeters_miles = 0.000000622;
private final double millimeter_centimeters = 10;
private final double millimeter_meters = 1000;
private final double millimeter_kilometers = 1000000;
public UnitConversion(String in, String out, double val)
{
input = in;
output = out;
value = val;
}
public String toString()
{
if (input.equals("mi"))
{
in = value * inch_miles;
input = "in";
}
else if (input.equals("ft"))
{
in = value * inch_feet;
input = "in";
}
else
{
in = value;
input = "in";
}
if (input.equals("km"))
{
mm = value * millimeter_kilometers;
input = "mm";
}
else if (input.equals("m"))
{
mm = value * millimeter_meters;
input = "mm";
}
else if (input.equals("cm"))
{
mm = value * millimeter_centimeters;
input = "mm";
}
else
{
mm = value;
input = "mm";
}
return value + input + " " + output;
}
public double getUnit()
{
if (input.equals("in"))
{
if (output.equals("ft"))
{
ft = in * inch_feet;
System.out.println(ft + "ft");
}
else if (output.equals("mi"))
{
mi = in * inch_miles;
System.out.println(mi + "mi");
}
else if (output.equals("mm"))
{
mm = in * inch_millimeters;
System.out.println(mm + "mm");
}
else if (output.equals("cm"))
{
cm = in * inch_centimeters;
System.out.println(cm + "cm");
}
else if (output.equals("m"))
{
m = in * inch_meters;
System.out.println(m + "m");
}
else if (output.equals("km"))
{
km = in * inch_kilometers;
System.out.println(km + "km");
}
else
{
System.out.println(in + "in");
}
}
else
{
if (output.equals("cm"))
{
cm = mm * millimeter_centimeters;
System.out.println(cm + "cm");
}
else if (output.equals("m"))
{
m = mm * millimeter_meters;
System.out.println(m + "m");
}
else if (output.equals("km"))
{
km = mm * millimeter_kilometers;
System.out.println(km + "km");
}
else if (output.equals("in"))
{
in = mm * millimeters_inch;
System.out.println(in + "in");
}
else if (output.equals("ft"))
{
ft = mm * millimeters_feet;
System.out.println(ft + "ft");
}
else if (output.equals("mi"))
{
mi = mm * millimeters_miles;
System.out.println(mi + "mi");
}
else
{
System.out.println(mm + "mm");
}
}
}
Basically, you need/want to give a String argument to System.out.println in order to display it.
Thus, when you use System.out.println with an Object (that is not a String) as the argument, Java actually outputs the result of the toString method on that object.
If you haven't overridden it, the Object class' implementation of toString is used: this is what gives you your current output: UnitConversion#76c5a2f7.
To learn more about how is this default toString implementation generating that String, you can refer to the javadoc entry for Object#toString.
Base on your output, and your provided code, yes! Rename String getInput() to String toString() and your current main() will work, or change your current main()
System.out.println(newConvert.getInput()); // <-- added .getInput()
I am currently writing a program that will read through a designated text file that checks the transaction values of each buy/sell/summary and checks the arithmetic such that if the transactions from the buy and sell statements do not equal the total transaction amount that was given in the summary then it outputs an error and closes the program. But currently my method scanMoneyValue has an error that says it's not returning a double, when in fact it is. Is there a different way I should go about returning the values from my method? Here is my code for reference:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class RecurrsionFileChecker {
public static void main(String[] args) {
int result;
//File Chooser Window
JFileChooser chooser = new JFileChooser("/home/nick/workspace/CS 1410-001/src/assignment03");
chooser.setDialogTitle("Please choose a file to be checked");
result = chooser.showOpenDialog(null);
//User Cancelled the chooser
if (result == JFileChooser.CANCEL_OPTION)
return;
File inputfile = chooser.getSelectedFile();
try
{
Scanner in = new Scanner(inputfile);
//Call Method to look at next transaction
scanNextTransaction(in);
}
catch (IOException e)
{
System.out.println("Could not read file: " + inputfile);
}
}
/**
* Returns double if the parameter Scanner has an error that does,
* not match the summary before it.
*
* #param s Any scanner
* #return double if Summaries don't match.
*/
public static double scanNextTransaction(Scanner s)
{
String buy, sell, summary, date;
double amount = 0, referenceValue, total = 0;
summary = s.next();
date = s.next();
referenceValue = scanMoneyValue(s);
while (s.hasNext())
{
if (s.next() == "Buy")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Sell")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Summary")
{
amount = scanSubSummary(s);
}
//add the transactions
total = total + amount;
}
return total;
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
public static double scanSubSummary(Scanner sub)
{
String summaryDate, transDate, transType;
int summarySubEntries, count = 0;
double transValue, summaryValue = 0, totalValue = 0, summaryAmount;
summaryDate = sub.next();
summaryAmount = scanMoneyValue(sub);
summarySubEntries = sub.nextInt();
while (count != summarySubEntries)
{
transType = sub.next();
if (transType == "Summary")
{
summaryValue = scanSubSummary(sub);
}
transValue = scanMoneyValue(sub);
totalValue = transValue + totalValue + summaryValue;
count++;
}
if (totalValue != summaryAmount)
{
System.out.print("Summary error on " + summaryDate + ".");
System.out.println("Amount is $" + summaryAmount + ", " + "should be $" + totalValue + ".");
}
return totalValue;
}
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
If the if condition fails then there's no return statement. You have a return inside of the condition but not outside. You'll need to add a return statement at the end, or throw an exception if not having a dollar sign is an error.
Okay, looking at the only relevant part of your code:
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
You do return a value if dollar starts with a $... but what do you expect to happen if it doesn't start with $? Currently you reach the end of the method without returning anything, which isn't valid.
You should probably throw an exception, if this is unexpected data that you can't actually handle.
Additionally, you shouldn't really use double for currency values anyway, due to the nature of binary floating point types. Consider using BigDecimal instead.
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
//NEED RETURN STATEMENT HERE
}
The error you get is because when you write a function all branches of that function must return a value of the correct type. In your case, if the if-statement fails it hits the end of the function without returning anything.
Its better to change it on
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
String amount = dollar.replaceAll("[^\\d.]+", "")
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
link on explain - Parsing a currency String in java
I have a DecimalFormat object which I'm using to format all of my double values to a set number of digits (let's say 2) when I'm displaying them. I would like it to normally format to 2 decimal places, but I always want at least one significant digit. For example, if my value is 0.2 then my formatter spits out 0.20 and that's great. However, if my value is 0.000034 my formatter will spit out 0.00 and I would prefer my formatter spit out 0.00003.
The number formatters in Objective-C do this very simply, I can just set a max number of digits I want to show at 2 and the minimum number of significant digits at 1 and it produces my desired output, but how can I do it in Java?
I appreciate any help anyone can offer me.
Kyle
Edit: I'm interested in rounding the values so 0.000037 displays as 0.00004.
It's not efficient, so if you perform this operation often I'd try another solution, but if you only call it occasionally this method will work.
import java.text.DecimalFormat;
public class Rounder {
public static void main(String[] args) {
double value = 0.0000037d;
// size to the maximum number of digits you'd like to show
// used to avoid representing the number using scientific notation
// when converting to string
DecimalFormat maxDigitsFormatter = new DecimalFormat("#.###################");
StringBuilder pattern = new StringBuilder().append("0.00");
if(value < 0.01d){
String s = maxDigitsFormatter.format(value);
int i = s.indexOf(".") + 3;
while(i < s.length()-1){
pattern.append("0");
i++;
}
}
DecimalFormat df = new DecimalFormat(pattern.toString());
System.out.println("value = " + value);
System.out.println("formatted value = " + maxDigitsFormatter.format(value));
System.out.println("pattern = " + pattern);
System.out.println("rounded = " + df.format(value));
}
}
import java.math.BigDecimal;
import java.math.MathContext;
public class Test {
public static void main(String[] args) {
String input = 0.000034+"";
//String input = 0.20+"";
int max = 2;
int min =1;
System.out.println(getRes(input,max,min));
}
private static String getRes(String input,int max,int min) {
double x = Double.parseDouble(((new BigDecimal(input)).unscaledValue().intValue()+"").substring(0,min));
int n = (new BigDecimal(input)).scale();
String res = new BigDecimal(x/Math.pow(10,n)).round(MathContext.DECIMAL64).setScale(n).toString();
if(n<max){
for(int i=0;i<max;i++){
res+="0";
}
}
return res;
}
}