Format String containing decimal values to Number using Scala
For example if var a="34.523" after formatting should be "34523".
Replace . with empty string?
scala> "12.343".replaceAll("\\.", "")
res0: String = 12343
There is also:
a.replace(".","")
Related
Why does NumberFormat(".##").format(17.46) leads to a string of 17.46 and not .46?
How can I achieve the latter, i.e. remove all digits in front of the decimal sign?
The NumberFormat only changes the way that a number is being displayed(basically, what formatting is). So you can't get the fractional part of the number(it doesn't work like pattern matching).
Instead, you can use:
var num = 17.46;
var fraction = num.toString().split('.')[1];
Note: you can use '.' + num.toString().split('.')[1] to get the fraction part with the starting dot.
You can read more about the ICU Formatting that NumberFormat uses in this link.
Just as an alternative to the other answer, you can try to remove the integer part before converting to String, and not after:
String formatFraction (num a){
num b = a.floor();
num c = a-b;
return NumberFormat(".##").format(c);
}
This way you can guarantee it will work despite of locale.
‘#’ in the NumberFormat class marks a single digit (omitted if the value is zero). So the number of hashtags after the decimal point denotes how many decimal places you want. For example:
double number = 12.1234;
NumberFormat(".#").format(number); //prints 12.1
NumberFormat(".##").format(number); //prints 12.12
NumberFormat(".###").format(number); //prints 12.123
NumberFormat(".####").format(number); //prints 12.1234
You could use substring and indexOf to remove everything before the decimal point, like so:
String str = "12.36";
String newStr = str.substring(str.indexOf('.') + 1);
//If you want to include the decimal point, remove the + 1.
Trying to create a simple function whereby a String value is passed in i.e. "1" and the formatter should return the value with leading zeros and 5 decimal points however instead of a dot '.' I'm trying to return it with a comma ','
This is what I have attempted however its not working because the decimalFormatter can only handle numbers and not a string. The end goal is to get from "1" to "000000001,00000" - character length is 14 in total. 5 0's after the comma and the remaining before the comma should be padded out 0's to fill the 9 digit requirement.
Another example would be going from "913" to "000000913,00000"
def numberFormatter (value: String): String =
{
import java.text.DecimalFormat
val decimalFormat = new DecimalFormat("%09d,00000")
val formattedValue = decimalFormat.format(value)
return formattedValue
}
Any help would be much appreciated. Thank you in advance.
It's easy enough to format a String padded with spaces, but with zeros not so much. Still, it's not so hard to roll your own.
def numberFormatter(value :String) :String =
("0" * (9 - value.length)) + value + ",00000"
numberFormatter("1") //res0: String = 000000001,00000
numberFormatter("913") //res1: String = 000000913,00000
Note that this won't truncate the input String. So if value is longer than 9 characters then the result will be longer than the desired 15 characters.
def f(value:String) = new java.text.DecimalFormat("000000000.00000").format(value.toFloat).replace(".", ",")
scala> f(913f)
res5: String = 000000913,00000
// Edit: Use .toFloat (or .toInt, .toLong, etc.) to convert your string to a number first.
(in swift language) For example " A + D " I want the string A to stay all the time but the value of D changes depending on let's say Hp, so when Hp is fd the string will be "A + fd" and etc
I mean like( "A + %s" % Hp ) for the string in python. Such as here: What does %s mean in Python?
If you are talking about %s, then it's a c-style formatting key, which awaits string variable or value in the list of arguments. In Swift, you compose strings using "\(variable)" syntax, which is called String interpolation, as explained in the documentation:
String Interpolation
String interpolation is a way to construct a new String value from a
mix of constants, variables, literals, and expressions by including
their values inside a string literal. You can use string interpolation
in both single-line and multiline string literals. Each item that you
insert into the string literal is wrapped in a pair of parentheses,
prefixed by a backslash ():
Source: official documentation
Example:
var myVar = "World"
var string = "Hello \(myVar)"
With non-strings:
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// Output: message is "3 times 2.5 is 7.5"
I am new to Scala and I want to calculate number of occurrences of a character in which start with a particular alphabet in a list of Strings.
For example-
val test1 : List[String] = List("zero","zebra","zenith","tiger","mosquito")
I have defined above List of Strings and I want to calculate count of all strings which start with "z".
I tried with below code-
scala> test2.count(s=> s.charAt(0) == "z")
res7: Int = 0
It is giving me result as 0. I am not sure what I am doing wrong. Please suggest.
Character values are delimited by single quotes. Double quotes are reserved for strings:
val test : List[String] = List("zero","zebra","zenith","tiger","mosquito")
test.count(_.charAt(0) == 'z') // 3: Int
you can simply use filter and find the length of the list
println(test1.filter(_.startsWith("z")).length)
If you want to ignore the cases (uppercase or lowercase) you can add .toLowerCase as
println(test1.filter(_.toLowerCase.startsWith("z")).length)
I hope the answer is helpful
How can I get users local decimal separator character from GWT. I have found the NumberFormat utility, which only returns the whole format and provides parsing.
NumberFormat.getDecimalFormat()...
Is there a (simple) way to get the decimal separator, thousand separator from the decimal format.
import com.google.gwt.i18n.client.LocaleInfo;
String decimalSeparator = LocaleInfo.getCurrentLocale().getNumberConstants().decimalSeparator();
String thousandSeparator = LocaleInfo.getCurrentLocale().getNumberConstants().groupingSeparator();
You can seed it with a known number and then parse it for the characters you want.
import com.google.gwt.i18n.client.NumberFormat;
NumberFormat fmt = NumberFormat.getDecimalFormat();
double value = 1234.5;
String formatted = fmt.format(value);
String thousandSeparator = formatted.substring(1,2);
String decimalSeparator = formatted.substring(5,6);