I have this code for my calculator:
public void onClick(View v) {
try {
double price = Double.parseDouble(InputPrice.getText()
.toString());
double percent = Double.parseDouble(InputPercent.getText()
.toString());
double priceValue = price * percent / 100.0f;
double percentValue = price - priceValue;
PriceToGet.setText(String.valueOf(priceValue));
PriceToPay.setText(String.valueOf(percentValue));
PriceToGet.setText(String.format("%.02f", priceValue));
PriceToPay.setText(String.format("%.02f", percentValue));
The Input and the Output are coming without commas like this:
Input: 333333333
Output: 134555.44
Output: 17475.66
This was just an example for Output and Input.
How do I like the user see them is:
Input: 333,333,333
Output: 134,555.44
Output: 17,475.66
Thanks
Update:
I added decimal in my onclick code:
DecimalFormat formatter = new DecimalFormat("#,###,###");
I used this code but its closing the App after I press the button:
String PriceToGet = formatter.format(String.format("%.02f", priceValue));
And when I am using this method:
String PriceToGet = formatter.format("%.02f", priceValue);
Its force me to change it to:
String PriceToGet = formatter.format(priceValue);
What to do?
You need to use DecimalFormat
You will find the complete answer here
This is how you can convert one of your integers to strings.
int x = 1000000;
DecimalFormat formatter = new DecimalFormat("#,###,###");
String number_string = formatter.format(x);
System.out.println(number_string);
// Outputs 1,000,000
This JS function from Css Tricks - http://css-tricks.com/snippets/javascript/comma-values-in-numbers/
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3) {
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
Related
In UWP c# in textbox.textchange event I'm using code like that
public static void wpisywanie_daty(TextBox sender)
{
var nowyWpis = "";
var plainText = sender.Text.Replace("/", "");
if (plainText.Length <= 5)
{
for (int i = 1; i <= plainText.Length; i++)
{
nowyWpis += plainText[i - 1];
if (i % 2 == 0) nowyWpis += "/";
}
sender.Text = nowyWpis;
sender.Select(sender.Text.Length, 0);
}
if (sender.Text.Length >= 10)
{
sender.IsEnabled = false;
sender.IsEnabled = true;
}
}
changing dinamicly text to format dd/mm/yyyy when you typing.
How to implement it in android c# xamarin?
When the code hit line sender.Text = nowyWpis; it rise textchanged eventhandler and start code from beginning.
i need to change the text="font roboto regular" to Font Roboto Regular in xml itself, how to do?
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="18sp"
android:textColor="#android:color/black"
android:fontFamily="roboto-regular"
android:text="font roboto regular"
android:inputType="textCapWords"
android:capitalize="words"/>
If someone looking for kotlin way of doing this, then code becomes very simple and beautiful.
yourTextView.text = yourText.split(' ').joinToString(" ") { it.capitalize() }
You can use this code.
String str = "font roboto regular";
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
for (String s : strArray) {
String cap = s.substring(0, 1).toUpperCase() + s.substring(1);
builder.append(cap + " ");
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(builder.toString());
Try this...
Method that convert first letter of each word in a string into an uppercase letter.
private String capitalize(String capString){
StringBuffer capBuffer = new StringBuffer();
Matcher capMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(capString);
while (capMatcher.find()){
capMatcher.appendReplacement(capBuffer, capMatcher.group(1).toUpperCase() + capMatcher.group(2).toLowerCase());
}
return capMatcher.appendTail(capBuffer).toString();
}
Usage:
String chars = capitalize("hello dream world");
//textView.setText(chars);
System.out.println("Output: "+chars);
Result:
Output: Hello Dream World
KOTLIN
val strArrayOBJ = "Your String".split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val builder = StringBuilder()
for (s in strArrayOBJ) {
val cap = s.substring(0, 1).toUpperCase() + s.substring(1)
builder.append("$cap ")
}
txt_OBJ.text=builder.toString()
Modification on the accepted answer to clean out any existing capital letters and prevent the trailing space that the accepted answer leaves behind.
public static String capitalize(#NonNull String input) {
String[] words = input.toLowerCase().split(" ");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (i > 0 && word.length() > 0) {
builder.append(" ");
}
String cap = word.substring(0, 1).toUpperCase() + word.substring(1);
builder.append(cap);
}
return builder.toString();
}
you can use this method to do it programmatically
public String wordFirstCap(String str)
{
String[] words = str.trim().split(" ");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < words.length; i++)
{
if(words[i].trim().length() > 0)
{
Log.e("words[i].trim",""+words[i].trim().charAt(0));
ret.append(Character.toUpperCase(words[i].trim().charAt(0)));
ret.append(words[i].trim().substring(1));
if(i < words.length - 1) {
ret.append(' ');
}
}
}
return ret.toString();
}
refer this if you want to do it in xml.
You can use
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
refer this How to capitalize the first character of each word in a string
android:capitalize is deprecated.
Follow these steps: https://stackoverflow.com/a/31699306/4409113
Tap icon of ‘Settings’ on the Home screen of your Android Lollipop
Device
At the ‘Settings’ screen, scroll down to the PERSONAL section and
tap the ‘Language & input’ section.
At the ‘Language & input’ section, select your keyboard(which is
marked as current keyboard).
Now tap the ‘Preferences’.
Tap to check the ‘Auto – Capitalization’ to enable it.
And then it should work.
If it didn't, i'd rather to do that in Java.
https://stackoverflow.com/a/1149869/2725203
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
Another approach is to use StringTokenizer class. The below method works for any number of words in a sentence or in the EditText view. I used this to capitalize the full names field in an app.
public String capWordFirstLetter(String fullname)
{
String fname = "";
String s2;
StringTokenizer tokenizer = new StringTokenizer(fullname);
while (tokenizer.hasMoreTokens())
{
s2 = tokenizer.nextToken().toLowerCase();
if (fname.length() == 0)
fname += s2.substring(0, 1).toUpperCase() + s2.substring(1);
else
fname += " "+s2.substring(0, 1).toUpperCase() + s2.substring(1);
}
return fname;
}
in kotlin, string extension
fun String?.capitalizeText() = (this?.toLowerCase(Locale.getDefault())?.split(" ")?.joinToString(" ") { if (it.length <= 1) it else it.capitalize(Locale.getDefault()) }?.trimEnd())?.trim()
Kotlin extension function for capitalising each word
val String?.capitalizeEachWord
get() = (this?.lowercase(Locale.getDefault())?.split(" ")?.joinToString(" ") {
if (it.length <= 1) it else it.replaceFirstChar { firstChar ->
if (firstChar.isLowerCase()) firstChar.titlecase(
Locale.getDefault()
) else firstChar.toString()
}
}?.trimEnd())?.trim()
As the best way for achieving this used to be the capitalize() fun, but now it got depricated in kotlin. So we have an alternate for this. I've the use case where I'm getting a key from api that'll be customized at front end & will be shown apparently. The value is coming as "RECOMMENDED_OFFERS" which should be updated to be shown as "Recommended Offers".
I've created an extension function :
fun String.updateCapitalizedTextByRemovingUnderscore(specialChar: String): String
that takes a string which need to be replaced with white space (" ") & then customise the words as their 1st character would be in caps. So, the function body looks like :
fun String.updateCapitalizedTextByRemovingUnderscore(
specialChar: String = "") : String {
var tabName = this
// removing the special character coming in parameter & if
exist
if (spclChar.isNotEmpty() && this.contains(specialChar)) {
tabName = this.replace(spclChar, " ")
}
return tabName.lowercase().split(' ').joinToString(" ") {
it.replaceFirstChar { if (it.isLowerCase())
it.titlecase(Locale.getDefault()) else it.toString() } }
}
How to call the extension function :
textView.text =
"RECOMMENDED_OFFERS".updateCapitalizedTextByRemovingUnderscore("_")
OR
textView.text = <api_key>.updateCapitalizedTextByRemovingUnderscore("_")
The desired output will be :
Recommended Offers
Hope this will help.Happy coding :) Cheers!!
capitalize each word
public static String toTitleCase(String string) {
// Check if String is null
if (string == null) {
return null;
}
boolean whiteSpace = true;
StringBuilder builder = new StringBuilder(string); // String builder to store string
final int builderLength = builder.length();
// Loop through builder
for (int i = 0; i < builderLength; ++i) {
char c = builder.charAt(i); // Get character at builders position
if (whiteSpace) {
// Check if character is not white space
if (!Character.isWhitespace(c)) {
// Convert to title case and leave whitespace mode.
builder.setCharAt(i, Character.toTitleCase(c));
whiteSpace = false;
}
} else if (Character.isWhitespace(c)) {
whiteSpace = true; // Set character is white space
} else {
builder.setCharAt(i, Character.toLowerCase(c)); // Set character to lowercase
}
}
return builder.toString(); // Return builders text
}
use String to txt.setText(toTitleCase(stringVal))
don't use android:fontFamily to roboto-regular. hyphen not accept. please rename to roboto_regular.
To capitalize each word in a sentence use the below attribute in xml of that paticular textView.
android:inputType="textCapWords"
I am working on writing a simple temperature conversion program, to familiarize myself with Android programming. The user types in a number to an EditText, and it converts it from Fahrenheit to Celsius, or vice versa, then puts the answer in a TextView. I want to append a Unicode Celsius/Fahrenheit symbol to the end of the answer before displaying it. When I don't have it appending the symbol, it works fine and displays the correct number, but when it is trying to append the symbol to the end, the output displays all wrong, with a long string of numbers at the end (and still no Unicode symbol).
Here's my code:
This is the converter utility class:
public class ConverterUtil {
//Convert to celsius
public static String convertFahrenheitToCelsius(float fahrenheit) {
float temperature = (fahrenheit - 32) * 5 / 9;
DecimalFormat df = new DecimalFormat("#.#");
return df.format(temperature) + R.string.celsius_symbol;
}
//Convert to fahrenheit
public static String convertCelsiustoFahrenheit(float celsius) {
float temperature = (celsius * 9) / 5 + 32; //Append the unicode Celsius symbol (\u2103), then return
DecimalFormat df = new DecimalFormat("#.#");a
return df.format(temperature) + R.string.fahrenheit_symbol; //Append the unicode Fahrenheit symbol (\u2109), then return
}
}
And this is where I call it:
public void calculateTemperature(){
RadioButton celsiusButton = (RadioButton) findViewById(R.id.button2);
TextView output = (TextView) findViewById(R.id.output);
if (text.getText().length() == 0) {
output.setText("");
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
String outputText = celsiusButton.isChecked() ? ConverterUtil.convertFahrenheitToCelsius(inputValue) : ConverterUtil.convertCelsiustoFahrenheit(inputValue);
output.setText(outputText);
}
If I take out the part where I append the Unicode symbols, it looks like this:
And if I put that back in, I get this:
How do I fix that?
Looks like the resourceID of your fahrenheit_symbol & celsius_symbol are getting appended to your text than the actual character.
Try this,
public class ConverterUtil {
//Convert to celsius
public static String convertFahrenheitToCelsius(Context context, float fahrenheit) {
float temperature = (fahrenheit - 32) * 5 / 9;
DecimalFormat df = new DecimalFormat("#.#");
return df.format(temperature) + context.getResources().getString(R.string.celsius_symbol);
}
//Convert to fahrenheit
public static String convertCelsiustoFahrenheit(Context context, float celsius) {
float temperature = (celsius * 9) / 5 + 32; //Append the unicode Celsius symbol (\u2103), then return
DecimalFormat df = new DecimalFormat("#.#");a
return df.format(temperature) + context.getResources().getString(R.string.fahrenheit_symbol); //Append the unicode Fahrenheit symbol (\u2109), then return
}
}
Change where you call it like this,
public void calculateTemperature(){
RadioButton celsiusButton = (RadioButton) findViewById(R.id.button2);
TextView output = (TextView) findViewById(R.id.output);
if (text.getText().length() == 0) {
output.setText("");
return;
}
float inputValue = Float.parseFloat(text.getText().toString());
String outputText = celsiusButton.isChecked() ? ConverterUtil.convertFahrenheitToCelsius(YourActivity.this, inputValue) : ConverterUtil.convertCelsiustoFahrenheit(YourActivity.this, inputValue);
output.setText(outputText);
}
Change
return df.format(temperature) + R.string.fahrenheit_symbol;
return df.format(temperature) + R.string.celsius_symbol;
to
return df.format(temperature) + getString(R.string.fahrenheit_symbol);
return df.format(temperature) + getString(R.string.celsius_symbol);
R.string.fahrenheit_symbol and R.string.celsius_symbol are both integers. You will need to look up the relevant string resource using Context.getResources().getString().
You will need to pass a Context (such as the calling Activity) to your ConverterUtil.
I have setup an edittext box and set the maxlength to 10. When I copy the edittext to a string myTitles. I need the myTiles to be 10 chars long and not dependent on what is entered in the edittext box.
myTitles[0] = TitlesEdit.getText().toString();
The edittext was filled with ABCD so I need to add 6 spaces or placeholders after the ABCD. I have seen other post with str_pad and substr without success
myTitles[0] = str_pad(strTest, 0, 10);
myTitles[0] = substr(strTest,0, 10);
Try something like
public static String newString(String str) {
for (int i = str.length(); i <= 10; i++)
str += "*";
return str;
}
This will return a String with * replaced for the empty ones.
So, for eg, if your String is abcde, then on calling newString() as below
myTitles[0] = newString("abcde");
will return abcde***** as the output.
String s = new String("abcde");
for(int i=s.length();i<10;i++){
s = s.concat("-");
}
Then output your string s.
Thank you Lal, I use " " to fill and it worked fine. here is my new code.
String strTest = TitlesEdit.getText().toString();
for (int i = strTest.length(); i <= 10; i++) {
strTest += " ";
}
Log.d("TAG", "String" + strTest);
myTitles[intLinenumber] = strTest;
I would like to read and write a Lowrance .usr file. This is a binary file with a particular data structure that I have managed to decode and have written a program in visual basic that does the necessary reading and writing. I am in the process of migrating this software to my android phone.
The Structure as I have defined it in VB is:
Public Structure WAYPOINT
Public wWaypointNum As Integer
Public dwLatitudeMM As Long
Public dwLongitudeMM As Long
Public dwAltitudeFT As Long
Public dwWaypointNmLength As Long
Public abWaypointName As Char()
Public wWaypointDescLength As Long
Public abWaypointDescription As Char()
Public dwWaypointTime As Long
Public dwWaypointSymbol As Long
Public wWaypointStatus As Integer
End Structure
The File is then read with the following code:
Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
Dim i As Integer
Dim objBR As BinaryReader
Dim objFS As FileStream
Dim objWP As New WAYPOINT
Dim objwVer As Integer
Dim objwSVer As Integer
Dim objNoWaypoints As Integer
Dim objNoRoutes As Integer
Dim TempLat As Double
Dim TempLng As Double
Dim LatString As String
Dim LngString As String
objFS = New FileStream("c:\Binary\Binary File\Binary File\waverider.usr", FileMode.Open)
objBR = New BinaryReader(objFS)
objBR.BaseStream.Seek(0, SeekOrigin.Begin)
objwVer = objBR.ReadInt16
objwSVer = objBR.ReadInt16
objNoWaypoints = objBR.ReadInt16
For i = 1 To objNoWaypoints
objWP = Nothing
With objWP
.wWaypointNum = objBR.ReadInt16
.dwLatitudeMM = objBR.ReadInt32
.dwLongitudeMM = objBR.ReadInt32
.dwAltitudeFT = objBR.ReadInt32
.dwWaypointNmLength = objBR.ReadInt32
.abWaypointName = objBR.ReadChars(.dwWaypointNmLength)
.wWaypointDescLength = objBR.ReadInt32
.abWaypointDescription = objBR.ReadChars(.wWaypointDescLength)
.dwWaypointTime = objBR.ReadInt32
.dwWaypointSymbol = objBR.ReadInt32
.wWaypointStatus = objBR.ReadInt16
End With
TempLat = objWP.dwLatitudeMM / EarthRad
TempLat = Math.Exp(TempLat)
TempLat = (2 * Math.Atan(TempLat)) - (Math.PI / 2)
TempLat = TempLat * RadToDeg
LatString = DegToDecMin(TempLat, "Lat")
TempLng = objWP.dwLongitudeMM / EarthRad
TempLng = Math.Exp(TempLng)
TempLng = (2 * Math.Atan(TempLng)) - (Math.PI / 2)
TempLng = TempLng * RadToDeg
LngString = DegToDecMin(TempLng, "Lng")
With lvWaypoints
Dim lv As ListViewItem = .Items.Add(objWP.abWaypointName)
With lv
.SubItems.Add(objWP.abWaypointDescription)
.SubItems.Add(LatString)
.SubItems.Add(LngString)
End With
End With
Next i
'\\ Read Routes
'objNoRoutes = objBR.ReadInt16 'Number of Routes
End Sub
The data is then decoded with:
Public Function DegToDecMin(ByVal DecDeg As Double, ByVal LatLng As String) As String
Dim ReturnValue As String
Dim Pos As String
If LatLng = "Lat" Then
If DecDeg < 0 Then Pos = "S" Else Pos = "N"
Else
If DecDeg < 0 Then Pos = "W" Else Pos = "E"
End If
Dim mDeg As Double = Math.Abs(DecDeg)
Dim mWholeDeg As Double = Math.Truncate(mDeg)
Dim mRemDegS As String = String.Format("{0:##.000}", (mDeg - mWholeDeg) * 60)
If InStr(mRemDegS, ".") = 2 Then mRemDegS = "0" & mRemDegS
If InStr(mRemDegS, ".") = 1 Then mRemDegS = "00" & mRemDegS
ReturnValue = mWholeDeg.ToString & Chr(176) & mRemDegS & "'" & Pos
Return ReturnValue
End Function
Are there similar functions in Java that can achieve the same objective
For the Java only syntax is changes according the Java Syntax,
First you need to create a bean file like below,
public class WayPoint
{
public int wWaypointNum;
public int dwLatitudeMM;
public dwLongitudeMM;
...
}
Second you required File API to read and write into and from file. For this you can use File, FileInputStream,FileOutputStream,DataInputStream,DataOutputStream.