Hi I have a excel file reading application which reads every cell in the file.
whenever a cell contains a numeric value the app is treating it a numeric cell.
For example the cell contains (40002547) the application will treat this as numeric cell. I cab get the value by using this code:
SONum = String.valueOf(cellSONum.getNumericCellValue());
Well that works fine. My Problem is it appends decimal at the end of the string. it will be (40002547.0). I need it to be as is. Thanks in advance
It's because cellSONum.getNumericCellValue() is returning a floating point type. If you force it to an integer before calling valueOf(), you should get the string representation in an integral form, if indeed that's what you want for all possibilities:
SONum = String.valueOf((int)cellSONum.getNumericCellValue());
You can see this in the following code:
class Test {
public static void main(String[]args) {
double d = 1234;
System.out.println(String.valueOf(d));
System.out.println(String.valueOf((int)d));
}
}
which outputs:
1234.0
1234
However, if you want to just get rid of .0 at the end of any string but allow non-integral values to survive, you can just remove the trailing text yourself:
class Test {
public static void main(String[]args) {
double d1 = 1234;
double d2 = 1234.567;
System.out.println(String.valueOf(d1).replaceFirst("\\.0+$", ""));
System.out.println(String.valueOf(d2).replaceFirst("\\.0+$", ""));
}
}
That snippet outputs:
1234
1234.567
Try with split().
SONum = String.valueOf(cellSONum.getNumericCellValue());
SONum = SONum.split("\\.")[0];
When you split 40002547.0 with . ,the split function returns two parts and the first one you need.
If you want to be sure you are not cutting of any valid decimals, you can use regexp also:
String pattern = "\.0+"; // dot followed by any number of zeros
System.out.println(String.valueOf(cellSONum.getNumericCellValue()).replaceAll(pattern, ""));
More on java regexp for example: http://www.vogella.com/articles/JavaRegularExpressions/article.html
As PaxDiablo also mentions, cellSONum.getNumericCellValue() returns a floating point.
You can cast this to Long or int to get rid of all behind the '.'
String SONum = String.valueOf(cellSONum.getNumericCellValue().longValue());
used as example:
String SONum = String.valueOf((new Double(0.5)).longValue());
SONum = ""+cellSONum.getNumericCellValue().split(".")[0];
try
double value = 23.0;
DecimalFormat df = new DecimalFormat("0.##");
System.out.println("bd value::"+ df.format(value))
Consider using BigDecimal.
You could simply say
BigDecimal scaledDecimal = new BigDecimal(value).setScale(0, RoundingMode.HALF_EVEN);
This will help in case your input is String and you need result also in String
1). Convert the string to Double using Double.parseDouble,
2). Type cast to int, then convert to string using String.valueOf()
private String formatText(String text) {
try {
return String.valueOf((int) Double.parseDouble(text));
} catch (NumberFormatException e) {
return text;
}
}
You can do Explicit type casting to remove the decimals,
double desvalue = 3.586;
int value = (int)desvalue;
Related
I want to remove a decimal point from a double value. I tried converting it to string
double intify(double a)
{
String s=Double.toString(a);
String s2=s.replaceAll(".","");
a=Double.parseDouble(s2);
return a;
}
If I pass 123.4567 it should return 1234567.
replaceAll replaces a regex. You should use replace instead:
String s2 = s.replace(".", "");
Instead of replaceAll use replace method of String:
String s2 = s.replace(".", "");
As "." has a special meaning in regex and replaceAll treats source string i.e. first parameter as regex.
The below solves the issue of an integer being passed in (123 or 123.0), or a double in scientific notation (1.23E7):
Double.parseDouble(Double.toString(a).replaceAll("[.](?0$)?",""));
In your code, just change the replaceAll string to [.](?0$)?, which states "Remove the decimal as well as the number 0 if it is right after the decimal and there's nothing after it".
Double i=Double.parseDouble("String with double value");
Log.i(tag,"display double "+i);
try{
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);// set as you need
String myStringmax = nf.format(i);
String result = myStringmax.replaceAll("[-+.^:,]","");
Double i=Double.parseDouble(result);
int max= Integer.parseInt(result);
}catch(Exception e){
System.out.println("ex="+e);
}
Your question isn't well-enough defined for a general answer, but if you want to get rid of the fractional part, just parse it as a double and then cast it to int or long.
I am trying to convert to int like this, but I am getting an exception.
String strHexNumber = "0x1";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
It would be a great help if someone can fix it.
Thanks.
That's because the 0x prefix is not allowed. It's only a Java language thing.
String strHexNumber = "F777";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println(decimalNumber);
If you want to parse strings with leading 0x then use the .decode methods available on Integer, Long etc.
int value = Integer.decode("0x12AF");
System.out.println(value);
Sure - you need to get rid of the "0x" part if you want to use parseInt:
int parsed = Integer.parseInt("100", 16);
System.out.println(parsed); // 256
If you know your value will start with "0x" you can just use:
String prefixStripped = hexNumber.substring(2);
Otherwise, just test for it:
number = number.startsWith("0x") ? number.substring(2) : number;
Note that you should think about how negative numbers will be represented too.
EDIT: Adam's solution using decode will certainly work, but if you already know the radix then IMO it's clearer to state it explicitly than to have it inferred - particularly if it would surprise people for "035" to be treated as octal, for example. Each method is appropriate at different times, of course, so it's worth knowing about both. Pick whichever one handles your particular situation most cleanly and clearly.
Integer.parseInt can only parse strings that are formatted to look just like an int. So you can parse "0" or "12343" or "-56" but not "0x1".
You need to strip off the 0x from the front of the string before you ask the Integer class to parse it. The parseInt method expects the string passed in to be only numbers/letters of the specified radix.
try using this code here:-
import java.io.*;
import java.lang.*;
public class HexaToInteger{
public static void main(String[] args) throws IOException{
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexadecimal value:!");
String s = read.readLine();
int i = Integer.valueOf(s, 16).intValue();
System.out.println("Integer:=" + i);
}
}
Yeah, Integer is still expecting some kind of String of numbers. that x is really going to mess things up.
Depending on the size of the hex, you may need to use a BigInteger (you can probably skip the "L" check and trim in yours ;-) ):
// Convert HEX to decimal
if (category.startsWith("0X") && category.endsWith("L")) {
category = new BigInteger(category.substring(2, category.length() - 1), 16).toString();
} else if (category.startsWith("0X")) {
category = new BigInteger(category.substring(2, category.length()), 16).toString();
}
How do I convert a double value with 10 digits for e.g 9.01236789E9 into a string 9012367890 without terminating any of its digits ?
I tried 9.01236789E9 * Math.pow(10,9) but the result is still double "9.01236789E18"
double d = 9.01236789E9;
System.out.println(BigDecimal.valueOf(d).toPlainString());
While 10 digits should be preservable with no problems, if you're interested in the actual digits used, you should probably be using BigDecimal instead.
If you really want to format a double without using scientific notation, you should be able to just use NumberFormat to do that or (as of Java 6) the simple string formatting APIs:
import java.text.*;
public class Test
{
public static void main(String[] args)
{
double value = 9.01236789E9;
String text = String.format("%.0f", value);
System.out.println(text); // 9012367890
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(0);
format.setGroupingUsed(false);
System.out.println(format.format(value)); // 9012367890
}
}
Try String.format("%20.0f", 9.01236789E9)
Note though it's never an exact value, so "preserving every digit" doesn't really make sense.
You can use it.
String doubleString = Double.toString(inValue)
inValue -----> Described by you.to what position you want to Change double to a string.
In this case, you can also do
double value = 9.01236789E9;
System.out.println((long) value); // prints 9012367890
I want to replace leading zeros in java with this expression found on this thread:
s.replaceFirst("^0+(?!$)", "")
But how can I make it work for values like -00.8899?
You can try with:
String output = "-00.8899".replace("^(-?)0*", "$1");
Output:
-.8899
Why are you dealing with a numeric value in a string variable?
Java being a strongly-typed language, you would probably have an easier time converting that to a float or double, then doing all the business logic, then finally formatting the output.
Something like:
Double d = Double.parseDouble(s);
double val = d; //mind the auto-boxing/unboxing
//business logic
//get ready to display to the user
DecimalFormat df = new DecimalFormat("#.0000");
String s = df.format(d);
http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
What is the best way to format the following number that is given to me as a String?
String number = "1000500000.574" //assume my value will always be a String
I want this to be a String with the value: 1,000,500,000.57
How can I format it as such?
You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).
You also need to convert that string into a number, this can be done with:
double amount = Double.parseDouble(number);
Code sample:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
This can also be accomplished using String.format(), which may be easier and/or more flexible if you are formatting multiple numbers in one string.
String number = "1000500000.574";
Double numParsed = Double.parseDouble(number);
System.out.println(String.format("The input number is: %,.2f", numParsed));
// Or
String numString = String.format("%,.2f", numParsed);
For the format string "%,.2f" - "," means separate digit groups with commas, and ".2" means round to two places after the decimal.
For reference on other formatting options, see https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Given this is the number one Google result for format number commas java, here's an answer that works for people who are working with whole numbers and don't care about decimals.
String.format("%,d", 2000000)
outputs:
2,000,000
Once you've converted your String to a number, you can use
// format the number for the default locale
NumberFormat.getInstance().format(num)
or
// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
I've created my own formatting utility. Which is extremely fast at processing the formatting along with giving you many features :)
It supports:
Comma Formatting E.g. 1234567 becomes 1,234,567.
Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".
Precision of 0 through 15.
Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).
Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).
The code can be found here. You call it like this:
public static void main(String[])
{
int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
String formatted = ValueFormat.format(1234567, settings);
}
I should also point out this doesn't handle decimal support, but is very useful for integer values. The above example would show "1.23M" as the output. I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.
you can also use the below solution
public static String getRoundOffValue(double value){
DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
return df.format(value);
}
public void convert(int s)
{
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}
public static void main(String args[])
{
LocalEx n=new LocalEx();
n.convert(10000);
}
You can do the entire conversion in one line, using the following code:
String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));
The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.
Here is the simplest way to get there:
String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result));
output:
10,987,655.88
The first answer works very well, but for ZERO / 0 it will format as .00
Hence the format #,##0.00 is working well for me.
Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.
According to chartGPT
Using DecimalFormat:
DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(yourNumber);
Using NumberFormat:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(true);
String formattedNumber = nf.format(yourNumber);
Using String.format():
String formattedNumber = String.format("%,.2f", yourNumber);
Note: In all the above examples, "yourNumber" is the double value that you want to format with a comma. The ".2f" in the format string indicates that the decimal places should be rounded to 2 decimal places. You can adjust this value as needed.