How to hide decimal value when it is = 0 - flutter

I am currently trying to render the price value of products using a widget in Flutter.
To do so, I pass the state and render it in the argument from the corresponding widget.
What I need to achieve is to hide the 2 decimals of my Double type priceValue and show them if they are != to 0.
Like so, if state.priceValue = 12.00 $ => should show 12
if state.priceValue = 12.30 $ => should show 12.30

String removeZero(double money) {
var response = money.toString();
if (money.toString().split(".").length > 0) {
var decmialPoint = money.toString().split(".")[1];
if (decmialPoint == "0") {
response = response.split(".0").join("");
}
if (decmialPoint == "00") {
response = response.split(".00").join("");
}
}
return response;
}
Edit: I added to check if the string contains a decimal point or not to avoid index out of bounds issue

Try this:
String price = "12.00$"
print(price.replaceAll(".00", ""));
Or refer to this: How to remove trailing zeros using Dart
double num = 12.50; // 12.5
double num2 = 12.0; // 12
double num3 = 1000; // 1000
RegExp regex = RegExp(r'([.]*0)(?!.*\d)');
String s = num.toString().replaceAll(regex, '');
But the second option will remove all trailing zeros so 12.30 will be 12.3 instead

Hello you could use an extension like that:
extension myExtension on double{
String get toStringV2{
final intPart = truncate();
if(this-intPart ==0){
return '$intPart';
}else{
return '$this';
}
}
}
To use the extension:
void main() {
double numberWithDecimals = 10.8;
double numberWithoutDecimals = 10.00;
//print
print(numberWithDecimals.toStringV2);
print(numberWithoutDecimals.toStringV2);
}

Related

How to extract specific string from whole string?

I have following strings :
String? hello = "(1.2,1.5 | 5)"
String? hi = "(2.3,3.2 | 9)"
Now I want to get
var newhello1 = 1.2,1.5
var newhello2 = 5
and
var newhi1 = 2.3,3.2
var newhi2 = 9
How to extract those text from that entire strings?
You can use the indexOf function combined with the substring to get the substrings as follows
var newhello1 = hello.substring(hello.indexOf('(') + 1, hello.indexOf('|')).trim(); //Use Trim() to get rid of any extra spaces
var newhello2 = hello.substring(hello.indexOf('|') + 1,hello.indexOf(')')).trim();
print(newhello1); //1.2,1.5
print(newhello2); //5
List<String> myformatter(String? data) {
if (data == null) return [];
List<String> ls = data.split("|");
for (int i = 0; i < ls.length; i++) {
ls[i] = ls[i].replaceAll("(", "").replaceAll(")", "").trim();
}
return ls;
}
main() {
String? hello = "(1.2,1.5 | 5)";
String? hi = "(2.3,3.2 | 9)";
final helloX = myformatter(hello);
print(helloX[0]); //1.2,1.5
print(helloX[1]); //5
final hiX = myformatter(hi);
print(hiX[0]); //2.3,3.2
print(hiX[1]); //9
}

split the string into equal parts flutter

There is a string with random numbers and letters. I need to divide this string into 5 parts. And get List. How to do it? Thanks.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
Should work:
List<String> list = [
'05b37ffe',
'4973959c',
'4d4f2d5c',
'a0c14357',
'49f8cc66',
];
I know there'a already a working answer but I had already started this so here's a different solution.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
List<String> list = [];
final divisionIndex = str.length ~/ 5;
for (int i = 0; i < str.length; i++) {
if (i % divisionIndex == 0) {
final tempString = str.substring(i, i + divisionIndex);
list.add(tempString);
}
}
log(list.toString()); // [05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d=1
; try{
d = (str.length/5).toInt();
print(d);
}catch(e){
d=1;
}
List datas=[];
for(int i=0;i<d;i++){
var c=i+1;
try {
datas.add(str.substring(i * d, d*c));
} catch (e) {
print(e);
}
}
print(datas);
}
OR
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d = (str.length / 5).toInt();
var data = List.generate(d - 3, (i) => (d * (i + 1)) <= str.length ? str.substring(i * d, d * (i + 1)) : "");
print(data);//[05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
If you're into one liners, with dynamic parts.
Make sure to import dart:math for min function.
This is modular, i.e. you can pass whichever number of parts you want (default 5). If you string is 3 char long, and you want 5 parts, then it'll return 3 parts with 1 char in each.
List<String> splitIntoEqualParts(String str, [int parts = 5]) {
int _parts = min(str.length, parts);
int _sublength = (str.length / _parts).ceil();
return Iterable<int>
//Initialize empty list
.generate(_parts)
.toList()
// Apply the access logic
.map((index) => str.substring(_sublength * index, min(_sublength * index + _sublength, str.length)))
.toList();
}
You can then use it such as print(splitIntoEqualParts('05b37ffe4973959c4d4f2d5ca0c1435749f8cc66', 5));
splitWithCount(String string,int splitCount)
{
var array = [];
for(var i =0 ;i<=(string.length-splitCount);i+=splitCount)
{
var start = i;
var temp = string.substring(start,start+splitCount);
array.add(temp);
}
print(array);
}

How to convert double into string with 2 significant digits?

So i have small double values and i need to convert them into string in order to display in my app. But i care only about first two significant digits.
It should work like this:
convert(0.000000000003214324) = '0.0000000000032';
convert(0.000003415303) = '0.0000034';
We can convert double to string, then check every index and take up to two nonzero (also .) strings. But the issue comes on scientific notation for long double.
You can check Convert long double to string without scientific notation (Dart)
We need to find exact String value in this case. I'm taking help from this answer.
String convert(String number) {
String result = '';
int maxNonZeroDigit = 2;
for (int i = 0; maxNonZeroDigit > 0 && i < number.length; i++) {
result += (number[i]);
if (number[i] != '0' && number[i] != '.') {
maxNonZeroDigit -= 1;
}
}
return result;
}
String toExact(double value) {
var sign = "";
if (value < 0) {
value = -value;
sign = "-";
}
var string = value.toString();
var e = string.lastIndexOf('e');
if (e < 0) return "$sign$string";
assert(string.indexOf('.') == 1);
var offset =
int.parse(string.substring(e + (string.startsWith('-', e + 1) ? 1 : 2)));
var digits = string.substring(0, 1) + string.substring(2, e);
if (offset < 0) {
return "${sign}0.${"0" * ~offset}$digits";
}
if (offset > 0) {
if (offset >= digits.length) return sign + digits.padRight(offset + 1, "0");
return "$sign${digits.substring(0, offset + 1)}"
".${digits.substring(offset + 1)}";
}
return digits;
}
void main() {
final num1 = 0.000000000003214324;
final num2 = 0.000003415303;
final v1 = convert(toExact(num1));
final v2 = convert(toExact(num2));
print("num 1 $v1 num2 $v2");
}
Run on dartPad

How to replace n occurrence of a substring in a string in dart?

I want to replace n occurrence of a substring in a string.
myString = "I have a mobile. I have a cat.";
How I can replace the second have of myString
hope this simple function helps. You can also extract the function contents if you don't wish a function. It's just two lines with some
Dart magic
void main() {
String myString = 'I have a mobile. I have a cat.';
String searchFor='have';
int replaceOn = 2;
String replaceText = 'newhave';
String result = customReplace(myString,searchFor,replaceOn,replaceText);
print(result);
}
String customReplace(String text,String searchText, int replaceOn, String replaceText){
Match result = searchText.allMatches(text).elementAt(replaceOn - 1);
return text.replaceRange(result.start,result.end,replaceText);
}
Something like that should work:
String replaceNthOccurrence(String input, int n, String from, String to) {
var index = -1;
while (--n >= 0) {
index = input.indexOf(from, ++index);
if (index == -1) {
break;
}
}
if (index != -1) {
var result = input.replaceFirst(from, to, index);
return result;
}
return input;
}
void main() {
var myString = "I have a mobile. I have a cat.";
var replacedString = replaceNthOccurrence(myString, 2, "have", "had");
print(replacedString); // prints "I have a mobile. I had a cat."
}
This would be a better solution to undertake as it check the fallbacks also. Let me list down all the scenarios:
If position is 0 then it will replace all occurrence.
If position is correct then it will replace at same location.
If position is wrong then it will send back input string.
If substring does not exist in input then it will send back input string.
void main() {
String input = "I have a mobile. I have a cat.";
print(replacenth(input, 'have', 'need', 1));
}
/// Computes the nth string replace.
String replacenth(String input, String substr, String replstr,int position) {
if(input.contains(substr))
{
var splittedStr = input.split(substr);
if(splittedStr.length == 0)
return input;
String finalStr = "";
for(int i = 0; i < splittedStr.length; i++)
{
finalStr += splittedStr[i];
if(i == (position - 1))
finalStr += replstr;
else if(i < (splittedStr.length - 1))
finalStr += substr;
}
return finalStr;
}
return input;
}
let's try with this
void main() {
var myString = "I have a mobile. I have a cat.I have a cat";
print(replaceInNthOccurrence(myString, "have", "test", 1));
}
String replaceInNthOccurrence(
String stringToChange, String searchingWord, String replacingWord, int n) {
if(n==1){
return stringToChange.replaceFirst(searchingWord, replacingWord);
}
final String separator = "#######";
String splittingString =
stringToChange.replaceAll(searchingWord, separator + searchingWord);
var splitArray = splittingString.split(separator);
print(splitArray);
String result = "";
for (int i = 0; i < splitArray.length; i++) {
if (i % n == 0) {
splitArray[i] = splitArray[i].replaceAll(searchingWord, replacingWord);
}
result += splitArray[i];
}
return result;
}
here the regex
void main() {
var myString = "I have a mobile. I have a cat. I have a cat. I have a cat.";
final newString =
myString.replaceAllMapped(new RegExp(r'^(.*?(have.*?){3})have'), (match) {
return '${match.group(1)}';
});
print(newString.replaceAll(" "," had "));
}
Demo link
Here it is one more variant which allows to replace any occurrence in subject string.
void main() {
const subject = 'I have a dog. I have a cat. I have a bird.';
final result = replaceStringByOccurrence(subject, 'have', '*have no*', 0);
print(result);
}
/// Looks for `occurrence` of `search` in `subject` and replace it with `replace`.
///
/// The occurrence index is started from 0.
String replaceStringByOccurrence(
String subject, String search, String replace, int occurence) {
if (occurence.isNegative) {
throw ArgumentError.value(occurence, 'occurrence', 'Cannot be negative');
}
final regex = RegExp(r'have');
final matches = regex.allMatches(subject);
if (occurence >= matches.length) {
throw IndexError(occurence, matches, 'occurrence',
'Cannot be more than count of matches');
}
int index = -1;
return subject.replaceAllMapped(regex, (match) {
index += 1;
return index == occurence ? replace : match.group(0)!;
});
}
Tested on dartpad.

Convert an arbitrarily long hexadecimal string to a number in Dart?

I need to convert a string of 8-character hexadecimal substrings into a list of integers.
For example, I might have the string
001479B70054DB6E001475B3
which consists of the following substrings
001479B7 // 1341879 decimal
0054DB6E // 5561198 decimal
001475B3 // 1340851 decimal
I'm currently using convert.hex to first convert the strings into a list of 4 integers (because convert.hex only handles parsing 2-character hex strings) and then adding/multiplying those up:
String tmp;
for(int i=0; i<=myHexString.length-8; i+=8){
tmp = myHexString.substring(i, i+8);
List<int> ints = hex.decode(tmp);
int dec = ints[3]+(ints[2]*256+(ints[1]*65536)+(ints[0]*16777216));
}
Is there a more efficient way to do this?
You can use int.parse('001479B7', radix: 16);
https://api.dartlang.org/stable/2.4.1/dart-core/int/parse.html
so your code will look like this :
void main() {
final fullString = '001479B70054DB6E001475B3';
for (int i = 0; i <= fullString.length - 8; i += 8) {
final hex = fullString.substring(i, i + 8);
final number = int.parse(hex, radix: 16);
print(number);
}
}
Since my Hex string came smaller than 8 elements of Byte, I did this.
String dumpHexToString(List<int> data) {
StringBuffer sb = StringBuffer();
data.forEach((f) {
sb.write(f.toRadixString(16).padLeft(2, '0'));
sb.write(" ");
});
return sb.toString();
}
String conertHexDecimal(String str1) {
final fullString = str1;
int number = 0;
for (int i = 0; i <= fullString.length - 8; i += 8) {
final hex = fullString.substring(i, i + 8);
number = int.parse(hex, radix: 16);
print(number);
}
return number.toString();
}
void executarConersao(Uint8List data){
String conersorHexDeVar = dumpHexToString(data);
conersorHexDeVar = conersorHexDeVar
.substring(3, conersorHexDeVar.length)
.replaceAll(' ', '')
.padLeft(8, '0');
conersorHexDeVar = conertHexDecimal(conersorHexDeVar);
print('data $conersorHexDeVar');
}
For anyone who wants to convert hexadecimal numbers to 2's component, Dart / Flutter has a builtin method - .toSigned(int):
var testConversion = 0xC1.toSigned(8);
print("This is the result: " + testConversion.toString()); // prints -63