Remove Trailing Zeros

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.


Remove insignificant trailing zeros from a number?

If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.

var n = 1.245000
var noZeroes = n.toString() // "1.245"

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, '');

Remove trailing zeros from decimal in SQL Server

A decimal(9,6) stores 6 digits on the right side of the comma. Whether to display trailing zeroes or not is a formatting decision, usually implemented on the client side.

But since SSMS formats float without trailing zeros, you can remove trailing zeroes by casting the decimal to a float:

select 
cast(123.4567 as DECIMAL(9,6))
, cast(cast(123.4567 as DECIMAL(9,6)) as float)

prints:

123.456700  123,4567

(My decimal separator is a comma, yet SSMS formats decimal with a dot. Apparently a known issue.)

number_format() php remove trailing zeros

You can add 0 to the formatted string. It will remove trailing zeros.

echo number_format(3.0, 1, ".", "") + 0; // 3

A Better Solution: The above solution fails to work for specific locales. So in that case, you can just type cast the number to float data type. Note: You might loose precision after type casting to float, bigger the number, more the chances of truncating the number.

echo (float) 3.0; // 3

Ultimate Solution: The only safe way is to use regex:

echo preg_replace("/\.?0+$/", "", 3.0); // 3
echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3

Snippet 1 DEMO

Snippet 2 DEMO

Snippet 3 DEMO

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 setprecisioncauses 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;
}

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));

Better way to remove trailing zeros from an integer

Just use str.rstrip():

def remove_zeros(number):
return int(str(number).rstrip('0'))

You could also do it without converting the number to a string, which should be slightly faster:

def remove_zeros(number):
while number % 10 == 0:
number //= 10
return number


Related Topics



Leave a reply



Submit