I have searched the internet but I could not find any solution (maybe, I've searched badly).
I want to convert the String "108595000.5" to a double and I have used these methods:
Double.parseDouble("108595000.5");
Double.valueOf("108595000.5");
Unfortunately, both of them return 1.08595E8.
How can I convert this String to double without problem?
The methods you have used do not return 1.08595E8, instead, they return the number and what you are complaining about is the representation of that number in the console (or as a String).
However, you can specify how to output a doubleyourself with a specified formatting, see this example:
public static void main(String[] args) {
String value = "108595000.5";
// use a BigDecimal to parse the value
BigDecimal bd = new BigDecimal(value);
// choose your desired output:
// either the String representation of a double (undesired)
System.out.println("double:\t\t\t\t\t" + bd.doubleValue());
// or an engineering String
System.out.println("engineering:\t\t\t\t" + bd.toEngineeringString());
// or a plain String (might look equal to the engineering String)
System.out.println("plain:\t\t\t\t\t" + bd.toPlainString());
// or you specify an amount of decimals plus a rounding mode yourself
System.out.println("rounded with fix decimal places:\t"
+ bd.setScale(2, BigDecimal.ROUND_HALF_UP));
}
double: 1.085950005E8
engineering: 108595000.5
plain: 108595000.5
rounded with fix decimal places: 108595000.50
try using
value = new BigDecimal(yourString);
doubleValue = value.doubleValue();
if you want the exact value.
If you want 2 numbers after ","
double a = yourDouble;
System.out.printf("%.2f",a)
Related
I have a number as
Double d = 100.000000;
I want to remove the decimal point and print the values as 100000000
(Note I am using java)
It is impossible. double doesn't store zeroes after decimal point so 1.0000 is equal to 1.0.
Hint: you can use BigDecimal for this. It have scale.
I'm afraid 100.000000 does not equal 100000000 and as mentioned by #talex, double doesn't store the zeros after the decimal point.
Your best bet is to use a String and remove the . manually:
String s = "100.000000";
System.out.println(s.replaceAll("\\.", "")); //note '.' needs to be escaped
Output:
100000000
You could parse it as a Double then if necessary.
Format the value using String.format and the remove the separator.
double d = 100.000;
String formatted = String.format(
Locale.US, //Using a Locale US to be sure the decimal separator is a "."
"%5f", //A decimal value with 5decimal
d) //The value to format
.replace(".", ""); //remove the separator
System.out.println(formatted);
100000000
Other examples :
100.000123456 > 100000123
You can see that the value is truncated, it is important to understand that.
Note that I have set the String to have 5 decimal number, but this up to you.
the double does not store the number as 100.0000 it just stored as 100.0 that means any unnecessary zeros on the right will be deleted but if the number was like this 100.01234 u can use this trick
Double d = 100.01245;
String text = Double.toString(d);
text.replace(".","");
d = Double.parseDouble(text);
or u can store the number as sting from the beginning
String text = "100.000000";
d.replace(".","");
double d = Double.parseDouble(text);
I want to convert double value up to two decimals. It is working fine for values like 6779.77,22334.22 but it doesn't work for value 33445.90,3334.30 it shows only 33445.9 and 3334.3 values does not show 0.
Why is it so?
public static String formatAmount(String number) {
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,##,##,###.##");
return formatter.format(amount);
}
# means that trailing zeroes can be omitted. Instead, you should use the 0 format character:
DecimalFormat formatter = new DecimalFormat("#,##,##,###.00");
// Here -------------------------------------------------^
I was wondering if there is an existing method to convert a formatted number String to number, such as "123,456.78" to 123456.78
Basically, unlike DecimalFormat function, which turns a double variable to a String following that a given format such as "###,###.##" pattern. I want to implement a reverse of this functionality, which turns a String with "###,###.##" format to a double. Is there APIs to do this?
Thank you.
You should have looked through the documentation for DecimalFormat and its superclass. You would have discovered that it has not only format methods, but also parse methods like this one.
The easiest way to do what you want is:
NumberFormat format = NumberFormat.getInstance();
Number value = format.parse(string);
// If you specifically want a double...
double d = value.doubleValue();
You will have to catch ParseException and deal with it. How you do that depends on what you want to do when your string does not represent a valid numeric value. If it's user input, you may want to ask the user to enter the text again.
Here is a simple way to do this
String number = "20,000,000";
int x = Integer.parseInt(number.replace(",", ""));
System.out.println(x);
You just replace the char's that not belong to a number with "" and then parse it into a primitive.
String number = "20,000,000.56";
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(5);
double x = Double.parseDouble(number.replace(",", ""));
System.out.println(df.format(x));
It is a bit different for a Double cause it will display the exponential output and you'll have to prevent that. The code above does that.
df.format(x)
Returns a String but you can cast it with the Double.parseDouble method
Here's a method using a Regex and the replace method if you have more than one delimiter and you know them all :
Let's say the delimiters here are "-" and ","
double x = Double.parseDouble(number.replace("[-,]", "");
i want to format my double value to 2 decimals and then make it "text to speech".
this is my code:
mares = mass * acc;
DecimalFormat df = new DecimalFormat("#.00");
df.format(mares);
String mare = String.format("The force is %f", df);
home.speak(mare,TextToSpeech.QUEUE_FLUSH, null);
but it crashes, i don't know why, i put 5 and 6 and it should multiply them and give me 30.00 or something like that.
when i remove DecimalFormat the result is 30.00000000000000, i just don't like it, too many zeros.
can someone help me please?
Thanks in advance!
Your DecimalFormat is returning the formatted string, but you are ignoring it, and passing it as an argument to String.format, which certainly isn't right.
Assign the return of df.format to a string for further reference:
String mare = df.format(mares);
Or pass the numeric value directly to String.format, with the appropriate format precision specified:
String mare = String.format("The force is %.2f", mares);
I'd like to use String.format() to format some BigDecimals as part of a string:
// Example:
String getPrice( String pattern )
{
BigDecimal price = basePrice.multiply( BigDecimal.ONE.add( vatRate ) );
BigDecimal priceInPence = price.multiply( new BigDecimal( "100" ) );
BigDecimal annualPrice = price.multiply( new BigDecimal( "365" ) );
return String.format( pattern, priceInPence, annualPrice );
}
String myPrice1 = getPrice( "Your price is %1$.3fp/day (£2$.2f/year) including VAT" );
// --> "Your price is 32.100p/day (£117.16/year) including VAT"
String myPrice2 = getPrice( "Around £%2$.0f annualy" );
// --> "Around £117 annually"
However the docs for String.format() say that any rounding of BigDecimals will be done with HALF_UP rounding, whereas I need HALF_EVEN.
I know how to manually set the scale of BigDecimals (Set specific precision of a BigDecimal) - but in this case I want to be able to use an arbitrary pattern string (including non-numeric pattern elements), so I won't know in advance what scale to use.
My question is therefore:
can I set the rounding mode used by String.format()? OR
is there another formatter or library that would format the numbers as in my example?
can I set the rounding mode used by String.format()?
Short answer: no.
is there another formatter or library that would format the numbers as in my example?
The BigDecimal is converted internally via new MathContext(compPrec) or plain HALF_UP.
You can take the code of java.util.Formatter of the latest (or your preferred) version Java and modify the creation of the MathContext to use HALF_EVEN. It should be 10-15minutes work. But then you need a custom method to mimic String.format:
public static String format(String format, Object... args) {
return new FormatterHALF_EVEN().format(format, args).toString();
}
Really "solid" advice to add 5000 lines of dead-weight code to your project! From what I see, the Formatter will not set scale unless it is already set to what is needed. So help it out, parse the format string and set your scale:
public static String getPrice(String pattern) {
BigDecimal basePrice = new BigDecimal("23");
BigDecimal vatRate = new BigDecimal("0.5");
BigDecimal price = basePrice.multiply(BigDecimal.ONE.add(vatRate));
BigDecimal priceInPence = price.multiply(new BigDecimal("100"));
BigDecimal annualPrice = price.multiply(new BigDecimal("365"));
Matcher matcher = Pattern.compile("%(\\d+)\\$.(\\d+)f").matcher(pattern);
while (matcher.find()) {
String index = matcher.group(1);
int scale = Integer.parseInt(matcher.group(2));
if (index.equals("1"))
priceInPence = priceInPence.setScale(scale, RoundingMode.HALF_EVEN);
else if (index.equals("2"))
annualPrice = annualPrice.setScale(scale, RoundingMode.HALF_EVEN);
}
return String.format(pattern, priceInPence, annualPrice);
}
with these numbers I get this output:
Your price is 3450.000p/day (£12592.50/year) including VAT
Around £12592 annualy
So it applies correct rounding.
Set the scale with the rounding mode you like, and include the values in the format string as strings, using BigDecimal#toString().