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.
Related
It used to be you could use substring to get a portion of a string. That has been deprecated in favor on string index. But I can't seem to make a string index out of integers.
var str = "hellooo"
let newindex = str.index(after: 3)
str = str[newindex...str.endIndex]
No matter what the string is, I want the second 3 characters. So and str would contain "loo". How can I do this?
Drop the first three characters and the get the remaining first three characters
let str = "helloo"
let secondThreeCharacters = String(str.dropFirst(3).prefix(3))
You might add some code to handle the case if there are less than 6 characters in the string
Say I have a string with n number of characters, but I want to trim it down to only 10 characters. (Given that at all times the string has greater that 10 characters)
I don't know the contents of the string.
How to trim it in such a way?
I know how to trim it after a CERTAIN character
String s = "one.two";
//Removes everything after first '.'
String result = s.substring(0, s.indexOf('.'));
print(result);
But how to remove it after a CERTAIN NUMBER of characters?
All answers (using substring) get the first 10 UTF-16 code units, which is different than the first 10 characters because some characters consist of two code units. It is better to use the characters package:
import 'package:characters/characters.dart';
void main() {
final str = "Hello 😀 World";
print(str.substring(0, 9)); // BAD
print(str.characters.take(9)); // GOOD
}
prints
➜ dart main.dart
Hello 😀
Hello 😀 W
With substring you might even get half a character (which isn't valid):
print(str.substring(0, 7)); // BAD
print(str.characters.take(7)); // GOOD
prints:
Hello �
Hello 😀
The above examples will fail if string's length is less than the trimmed length. The below code will work with both short and long strings:
import 'dart:math';
void main() {
String s1 = 'abcdefghijklmnop';
String s2 = 'abcdef';
var trimmed = s1.substring(0, min(s1.length,10));
print(trimmed);
trimmed = s2.substring(0, min(s2.length,10));
print(trimmed);
}
NOTE:
Dart string routines operate on UTF-16 code units. For most of Latin and Cyrylic languages that is not a problem since all characters will fit into a single code unit. Yet emojis, some Asian, African and Middle-east languages might need 2 code units to encode a single character. E.g. '😊'.length will return 2 although it is a single character string. See characters package.
I think this should work.
String result = s.substring(0, 10);
To trim a String to a certain number of characters. The. code below works perfectly well:
// initialise your string here
String s = 'one.two.three.four.five';
// trim the string by getting the first 10 characters
String trimmedString = s.substring(0, 10);
// print the first ten characters of the string
print(trimmedString);
Output:
one.two.th
i hope this helps
You can do this in multiple ways.
'string'.substr(start, ?length) USE :- 'one.two.three.four.five'.substr(0, 10)
'string'.substring(start, ?end) USE :- 'one.two.three.four.five'.substring(0, 10)
'string'.slice(start, ?end) USE :- 'one.two.three.four.five'.slice(0, 10)
To trim all trailing/right characters by specified characters, use the method:
static String trimLastCharacter(String srcStr, String pattern) {
if (srcStr.length > 0) {
if (srcStr.endsWith(pattern)) {
final v = srcStr.substring(0, srcStr.length - 1 - pattern.length);
return trimLastCharacter(v, pattern);
}
return srcStr;
}
return srcStr;
}
For example, you want to remove all 0 behind the decimals
$123.98760000
then, call it by
trimLastCharacter("$123.98760000", "0")
output:
$123.9876
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.
I'm trying to create a string from hex values in an array, but whenever a hex in the array starts with a zero it disappears in the resulting string as well.
I use String(value:radix:uppercase) to create the string.
An example:
Here's an array: [0x13245678, 0x12345678, 0x12345678, 0x12345678].
Which gives me the string: 12345678123456781234567812345678 (32 characters)
But the following array: [0x02345678, 0x12345678, 0x02345678, 0x12345678] (notice that I replaced two 1's with zeroes).
Gives me the string: 234567812345678234567812345678 (30 characters)
I'm not sure why it removes the zeroes. I know the value is correct; how can I format it to keep the zero if it was there?
The number 0x01234567 is really just 0x1234567. Leading zeros in number literals don't mean anything (unless you are using the leading 0 for octal number literals).
Instead of using String(value:radix:uppercase), use String(format:).
let num = 0x1234567
let str = String(format: "%08X", num)
Explanation of the format:
The 0 means to pad the left end of the string with zeros as needed.
The 8 means you want the result to be 8 characters long
The X means you want the number converted to uppercase hex. Use x if you want lowercase hex.
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);