How to remove trailing zeros using Dart
I made regular expression pattern for that feature.
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, '');
Javascript: Remove last decimal if zero
You could check the last digit of a stringed number and remove the last zero, if exists.
console.log([1.5, 1.49, 1.579].map(v => { var temp = v.toFixed(3); return temp.slice(-1) === '0' ? temp.slice(0, -1) : temp;}));
Remove trailing zeros
Is it not as simple as this, if the input IS a string? You can use one of these:
string.Format("{0:G29}", decimal.Parse("2.0044"))
decimal.Parse("2.0044").ToString("G29")
2.0m.ToString("G29")
This should work for all input.
Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:
However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved
Update Konrad pointed out in the comments:
Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation.
string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US")))
will give "1E-08" as the result.
How to remove trailing zeros from a binary number
Here is a brute force approach:
long long remove_trailing_zeroes(long long v) {
if (v != 0) {
while ((v & 1) == 0)
v /= 2;
}
return v;
}
Here is a direct approach for unsigned numbers, but the division might be more costly than the above iteration:
unsigned long long remove_trailing_zeroes(unsigned long long v) {
if (v != 0) {
// v and (v - 1) differ only in the trailing 0 bits plus 1
// shifting v ^ (v - 1) right by 1 and adding 1 gives the power of 2
// by which to divide v to remove all trailing 0 bits
v /= (((v ^ (v - 1)) >> 1) + 1);
}
return v;
}
harold suggested this simplification:
unsigned long long remove_trailing_zeroes(unsigned long long v) {
if (v != 0) {
// `-v`, which is `(~v + 1)` has all bits flipped except the least
// significant 1 bit.
// dividing v by `-v & v` shifts all trailing zero bits out,
v /= -v & v;
}
return v;
}
Which can be simplified as a single expression:
unsigned long long remove_trailing_zeroes(unsigned long long v) {
return v ? v / (-v & v) : v;
}
To avoid the division, you could count the number of bits in v ^ (v - 1)
with an efficient method and shift v
right by one less than this number. This would work for 0
as well so you would get branchless code.
You can find other methods in the fascinating word of Bit Twiddling Hacks
Remove trailing zeros Intl.NumberFormat - JavaScript
Use maximumSignificantDigits
maximumFractionDigits
. Something like:
function getAmount(number) {
if ((number | 0) < number) {
return Intl.NumberFormat('sv-SE', {
style: 'currency',
currency: 'SEK'
}).format(number)
}
return Intl.NumberFormat('sv-SE', {
style: 'currency',
currency: 'SEK',
maximumFractionDigits: 0
}).format(number);
}
console.log(getAmount(200));
console.log(getAmount(200.23));
Using RegEx how do I remove the trailing zeros and decimal also if needed
^(\d+(?:\.\d*?[1-9](?=0|\b))?)\.?0*$
Demo here.
explanation
^ //Beginning of line
( //Start collecting our group
\d+ //All digits before decimal
(?: //START-Non collecting group
\. //Decimal point
\d*? //It should actually be [0-9]
[1-9] //Last significant digit after decimal
(?=0|\b) //Either should be followed by zero or END OF WORD
)? //END-Non collecting group
//The non-capturing group after decimal is optional
) //End collecting our group
\.? //Optional decimal (decimal collected if it wasn't used earlier)
0* //All the remaining zeros no + as all digits might be significant that is no ending zero
$ //End of line.
Remove trailing zero in C++
This is one thing that IMHO is overly complicated in C++. Anyway, you need to specify the desired format by setting properties on the output stream. For convenience a number of manipulators are defined.
In this case, you need to set fixed
representation and set precision
to 2 to obtain the rounding to 2 decimals after the point using the corresponding manipulators, see below (notice that setprecision
causes rounding to the desired precision). The tricky part is then to remove trailing zeroes. As far as I know C++ does not support this out of the box, so you have to do some string manipulation.
To be able to do this, we will first "print" the value to a string and then manipulate that string before printing it:
#include <iostream>
#include <iomanip>
int main()
{
double value = 12.498;
// Print value to a string
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << value;
std::string str = ss.str();
// Ensure that there is a decimal point somewhere (there should be)
if(str.find('.') != std::string::npos)
{
// Remove trailing zeroes
str = str.substr(0, str.find_last_not_of('0')+1);
// If the decimal point is now the last character, remove that as well
if(str.find('.') == str.size()-1)
{
str = str.substr(0, str.size()-1);
}
}
std::cout << str << std::endl;
}
Related Topics
How to Import File from Public Folder in React Application
Check Whether an Input String Contains a Number in JavaScript
How to Merge an Array of Objects With Same Keys in Es6 JavaScript
Concatenate Json to a String in JavaScript
Select Value of Input Element Inside HTML Table Using Jquery
How to Apply Count Up Function to Multiple Values on the Page
How to Change Text Value Upon Button Press in React Native
Image Resizing Client-Side With JavaScript Before Upload to the Server
How to Force Update Child Component from Parent Component in Reactjs
Show Questions One At a Time in Quiz Website in HTML
How to Get Around .Push Is Not a Function in JavaScript
How to Convert File to Base64 in JavaScript
How to Partition Input Field to Appear as Separate Input Fields on Screen
Disable Chrome Strict Mime Type Checking
Webpack: Module Not Found: Error: Can't Resolve (With Relative Path)
Group By, and Sum, and Generate an Object for Each Array in JavaScript