PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label numbers. Show all posts
Showing posts with label numbers. Show all posts

Wednesday, November 2, 2022

[FIXED] How to delete lines which contains only numbers in python?

 November 02, 2022     file, numbers, python, text-files     No comments   

Issue

I have a large text file in Python. Firstly, I want to read the text then, delete lines which have only numbers. Then, I open a new text file and write with my changes.

If the line contains numbers and strings, I want to keep them. I tried with isdigit and regex but I couldn't...

e.g. I tried: but it deletes all lines that contain numbers.

    if not all(line.isdigit() for line in text_data):

new question:

line1: 324 4234 23456

if I have a line which contains numbers and space only like line1, how I skip them to my new text file?


Solution

Strip whitespace from the line before checking if it is all numbers.

for line in text_data:
    if line.strip().isdigit():
        # do what is required for a line with all numbers
    else:
        # do what is required for an alphanumeric line


Answered By - wwii
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 17, 2022

[FIXED] Why does Math.Round give me two different values?

 October 17, 2022     c#, floating, integer, math.round, numbers     No comments   

Issue

class Program {
    static void Main(string[] args) {
      double d = 120.5;
      Console.WriteLine(Math.Round(120.5)); //121
      Console.WriteLine(Math.Round(d)); // 120
    }
}

When a variable is passed as an argument into Math.Round it produces an answer similar to Convert.ToInt32 where floating numbers are rounded off to the nearest even number if the trailing tenth number is 0.5.

Anyone can kindly explain? Thanks in advance.

Thanks for the answers! I use Replit most of the time, that's the output I got. But seeing the replies, I tested it again in VS and I got both 120. I guess there's a bug in replit? Kindly refer to attachments.

enter image description here

enter image description here


Solution

I tested your code and returns 120 in two modes. It is good to know that the Math.Round() has features that you can use.

For example, you can say to always round to a number that is further from zero:

 double d = 120.5;

 Console.WriteLine(Math.Round(d,MidpointRounding.AwayFromZero)); //always 121

or final digit is even:

 Console.WriteLine(Math.Round(d,MidpointRounding.ToEven)); //always 120

and other features like MidpointRounding.ToNegativeInfinity, MidpointRounding.ToPositiveInfinity ....



Answered By - hossein sabziani
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 17, 2022

[FIXED] How to skip certain numbers in a for-loop?

 August 17, 2022     c, for-loop, numbers, output, skip     No comments   

Issue

I started practicing a for loop in C and so far I understand the main principle behind it. But I can't figure out how to get the following output:

1 2 3  5 6 7  9 10 11 ...

I managed to print 1 to 12 with the following for loop but how can I skip 4 and 8 or how to skip any number in general?

for(int i = 1; i < 12; i++)
{
    printf("%d", i);
}

Solution

the simplest solution would be to check with an if statement for any values that you don't want. if you have a rule like not printing all numbers that are divisible by 4 you can make your if statement like this

if(i % 4 == 0)
{
   //print
}

there is no way to do it specifically with the for loop expression.



Answered By - Gilad
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, August 13, 2022

[FIXED] How do I combine my two Javascript functions to allow three digit commas and one decimal point?

 August 13, 2022     decimal, javascript, jquery, numbers     No comments   

Issue

I'm trying to combine two Javascript functions into one code. The first function which targets the ".commas" class, inserts a comma after 3 digits. The second called "function floatKey" only allows one decimal point before the last two digits.

I tried inserting the ".commas" class function into the second one and removed the "event.preventDefault if statement", but the result was iffy - it allowed more digits after the decimal along with commas. It also removed all the commas before the decimal point. I also allowed "charCode 44" as an exception to the "if statement" in "function floatKey" but all it did was show and instantly disappear comma inserts. How would I combine these two functions to make both work?

My codes: ".commas" class function:

$(".commas").keyup(function(event){
  if(event.which >= 37 && event.which <= 40){
      event.preventDefault();
  }
  var $this = $(this);
  var num = $this.val().replace(/,/gi, "");
  var num2 = num.split(/(?=(?:\d{3})+$)/).join(",");
  console.log(num2);
  $this.val(num2);
});

function "floatKey":

function floatKey(el, evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var number = el.value.split('.');
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    if(number.length>1 && charCode == 46){
        return false;
    }
    var caratPos = getSelectionStart(el);
    var dotPos = el.value.indexOf(".");
    if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
        return false;
    }
    return true;
}

I hope I explained my problem clear enough, thank you for your help.


Solution

Please see: Javascript Thousand Separator / string format

Consider the following.

$(function() {
  function formatFloat(nStr) {
    var result;
    var dec = nStr.indexOf(".");
    var x;
    if (dec > 0) {
      x = nStr.split(".");
      x[0] = parseInt(x[0]);
    } else {
      x = [];
      x.push(parseInt(nStr));
    }
    result = x[0].toLocaleString('en');
    if (dec > 0) {
      result = result + "." + x[1].slice(0,2);
    }
    return result;
  }
  $(".commas").keyup(function(e) {
    e.preventDefault();
    // Strip previous formatting
    var v = $(this).val().split(",").join("");
    // enter new formatting
    $(this).val(formatFloat(v));
    return false;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Number: <input class="commas" type="text" /></p>

In this we split the string if there is a decimal . point. We can use .toLocaleString("en") to localize the number.

The toLocaleString() method returns a string with a language-sensitive representation of this number.

This does all the heavy comma lifting. We then add back the decimal value if needed.

Hope that helps.



Answered By - Twisty
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 12, 2022

[FIXED] How to extract first number after decimal point in value

 August 12, 2022     decimal, numbers, oracle, sql, truncate     No comments   

Issue

I have an age column which calculates age for each member in my report.The output is a whole number followed by a decimal point and numbers. I would like the first number only right after the decimal point .

I tried trunc but it gives me everything before the decimal and then the number I want after .Then I tried to trunc with a call out with a comma and it doesnt work.

trunc(age,',')

Example -

age 15.7

expected output 7


Solution

try like below

select substr(to_char(15.7,'9999.0'),-1,1) as col from dual
 it will return 7


Answered By - Zaynul Abadin Tuhin
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 11, 2022

[FIXED] How can I update a table to insert decimal points at a fixed position in numbers?

 August 11, 2022     decimal, numbers, sql, sql-server, sql-server-2014     No comments   

Issue

I am using Microsoft SQL Server 2014 and have a table with three columns and the field data type is Decimal(38,0).

I want to update each row of my table to insert a decimal point after the first two digits. For example, I want 123456 to become 12.3456. The numbers are different lengths; some are five digits, some are seven digits, etc.

My table is:

+-------------+-------+-------+
| ID          |   X   |   Y   |
+-------------+-------+-------+
| 1200        | 321121| 345000|
| 1201        | 564777| 4145  |
| 1202        | 4567  | 121444|
| 1203        | 12747 | 789887|
| 1204        | 489899| 124778|
+-------------+-------+-------+

And I want to change this to:

+-------------+--------+--------+
| ID          |   X    |   Y    |
+-------------+--------+--------+
| 1200        | 32.1121| 34.5000|
| 1201        | 56.4777| 41.45  |
| 1202        | 45.67  | 12.1444|
| 1203        | 12.747 | 78.9887|
| 1204        | 48.9899| 12.4778|
+-------------+--------+--------+

My code is:

Update [dbo].[UTM]
     SET [X] = STUFF([X],3,0,'.')
         [Y] = STUFF([X],3,0,'.')

And I tried this:

BEGIN
DECLARE @COUNT1 int;
DECLARE @COUNT2 int;
DECLARE @TEMP_X VARCHAR(255);
DECLARE @TEMP_Y VARCHAR(255);
DECLARE @TEMP_main VARCHAR(255);

SELECT @COUNT1 = COUNT(*) FROM [UTM];
SET @COUNT2 = 0;

    WHILE(@COUNT2<@COUNT1)
    BEGIN
        SET @TEMP_main = (SELECT [id] from [UTM] order by [id] desc offset @COUNT2 rows fetch next 1 rows only);
        SET @TEMP_X = (SELECT [X] from [UTM] order by [id] desc offset @COUNT2 rows fetch next 1 rows only);
        SET @TEMP_Y = (SELECT [Y] from [UTM] order by [id] desc offset @COUNT2 rows fetch next 1 rows only);

        UPDATE [dbo].[UTM]
           SET [X] = CONVERT(decimal(38,0),STUFF(@TEMP_X,3,0,'.'))
              ,[Y] = CONVERT(decimal(38,0),STUFF(@TEMP_Y,3,0,'.'))
           WHERE [id] = @TEMP_main;

        SET @COUNT2 = @COUNT2  +  1
    END

END

Solution

This runs on an assumption from a previously deleted post (that you have negative number as well).

Firstly, as you're using a decimal(38,0) you can't store values with any kind of precision, thus you need to change the data type as well. This provides the results you appear to be looking for:

USE Sandbox;
GO

CREATE TABLE dbo.SampleTable (ID int,
                              X decimal(38,0),
                              Y decimal(38,0));
INSERT INTO dbo.SampleTable (ID,
                             X,
                             Y)
VALUES (1200,321121,345000), 
       (1201,564777,4145  ), 
       (1202,4567  ,121444), 
       (1203,12747 ,789887), 
       (1204,489899,124778),
       (1205,-32472,-27921);
GO
--Fix the datatype
ALTER TABLE dbo.SampleTable ALTER COLUMN X decimal(10,4); --Based on data provided, may need larger scale
ALTER TABLE dbo.SampleTable ALTER COLUMN Y decimal(10,4); --Based on data provided, may need larger scale
GO

--update the data
UPDATE dbo.SampleTable
SET X = STUFF(ABS(CONVERT(int,X)),3,0,'.') * CONVERT(decimal(10,4),CASE WHEN X < 0 THEN -1.0 ELSE 1.0 END),
    Y = STUFF(ABS(CONVERT(int,Y)),3,0,'.') * CONVERT(decimal(10,4),CASE WHEN Y < 0 THEN -1.0 ELSE 1.0 END);

SELECT *
FROM dbo.SampleTable;
GO

DROP TABLE dbo.SampleTable;

Note that you won't get a value like 41.45, but instead 41.4500. If you don't want to display trailing 0's you need to do the formatting in your presentation layer (otherwise you'd have to store the values as a varchar, and that's a very bad idea).



Answered By - Larnu
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get top and bottom number of a number in iOS Swift?

 August 11, 2022     decimal, ios, numbers, swift     No comments   

Issue

I have a number like 73
how get max and min like 70 and 80.
or 173 I want to get 170 and 180 etc.


Solution

ceil(73/10) * 10 // round up 80
round(73/10) * 10 // round down 70

Playground: enter image description here

EDIT: Here just provide an idea.

let value: Int = 75

func min(_ value: Int) {
    value - value % 10
}

func max(_ value: Int) {
    value + 10 - value % 10
}

min(value)

max(value)


Answered By - William Hu
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make number result without decimal

 August 11, 2022     android, decimal, java, numbers, rounding     No comments   

Issue

I have problem with code. I will copy simplified code, with two editext and one textview and button. With this code if value in editext1 is "100" and other editext2 is"60" I get result answer "40.0" and it should be "40". Thanks

for code:

public class MainActivity extends AppCompatActivity {
    EditText number1;
    EditText number2;
    Button Add_button3;
    TextView descr;
    int ans=0;
    private BreakIterator view;

    @SuppressLint("CutPasteId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //
        number1=(EditText) findViewById(R.id.editText_first_no);
        number2=(EditText) findViewById(R.id.editText_second_no);
        Add_button3=(Button) findViewById(R.id.add_button3);
        descr = (TextView) findViewById(R.id.textView_DESC);

        //
        Add_button3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                double num1 = Double.parseDouble(number1.getText().toString());
                double num2 = Double.parseDouble(number2.getText().toString());
                double sump = num1 - num2;

                descr.setText(Double.toString(sump));
            }
        });
    }
}

Solution

There are two options, casting and using Math class.

To cast: descr.setText(Integer.toString((int)sump));

That approach has only one downside, you are losing information.

So if you abstract double sump = 5.0 - 3.3; which equals: 1.7000000000000002 the casting gives you '1'.

In my opinion better way is to use Math class and in particular method random() that is:

descr.setText(Math.round(sump));

The method also will remove some data but it will round the number to the closest whole number (integer) which is a preferred way to deal with similar situations.

For more please check: How to convert float to int with Java



Answered By - Konrad
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to merge two Hex numbers to one number and then convert it into decimal.?

 August 11, 2022     c, decimal, hex, merge, numbers     No comments   

Issue

I am making a C program in which I have two hex numbers, i.e. num1=25 num2=71 which are in hex. I want to make it as num3=2571 and then I have to convert 2571 into a decimal number. How do I do this? Please help, Thanks!


Solution

Just shift the digits and combine

int num1,num2,num3;
num1=0x25;
num2=0x71;
num3=(num1<<8)|(num2);
printf("%x %d",num3,num3);

You need to place 25 (0025) followed by 71 (0071) in a variable, so you have to left shift the first number by 8 bits (0025 to 2500) and combine it with num2. Logical Or is the equivalent for combining, hence the | symbol.



Answered By - Nerdy
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to convert a very large decimal number to a string?

 August 11, 2022     decimal, javascript, numbers, string     No comments   

Issue

I want to convert the decimal number 123.456e+304 to the string "123.456e+304" (the position of the decimal point . should not be changed).

Here is what I've tried, but all of them return the same result: 1.23456e+306 (the position of the decimal point has been changed, and it has also replaced 304 with 306).

var e = 123.456e+304;

console.log(e.toString());
console.log((e).toString());
console.log(e .toString());
console.log(e.toFixed());
console.log(String(e));
console.log((new String(e)).toString());
console.log(`${e}`);
console.log('' + e);
console.log(e + '');
console.log(''.split.call(e, '').join(''));

Is there any way to convert it to the expect string "123.456e+304"?


Solution

It is not possible, because once you assigned:

var e = 123.456e+304;

and is processed by the JavaScript interpreter, e is just a number internally represented by IEEE 754 a number equivalent to 1.23456e+306 and it has "no memory" where your decimal point was. So no matter what you do, you can't know where the decimal point was and let you move it to where you want it to be in a string.

In order "to have the knowledge" of where the decimal point was, you need to have a string to begin with, but that's also the result that you want.



Answered By - nonopolarity
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 10, 2022

[FIXED] How to truncate a number

 August 10, 2022     decimal, html, numbers, perl, truncate     No comments   

Issue

I should display numbers to a table. But I need The number has only two characters after a comma. How to do it correctly.

            $score =  $schet;
%>
            <tr class="ten" >
                <td class="six" > <%= $schet %></td>
                <td> <%= $d->start %></td>
                <td> <%= $d->end   %></td>
            </tr>
<%
        }

Solution

Use sprintf:

my $number_with_two_decimal_places = sprintf '%.2f', $float;


Answered By - choroba
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What do 48 and 87 values refer to when converting hexadecimal to decimal number in C?

 August 10, 2022     base, c, decimal, hex, numbers     No comments   

Issue

I am trying to understand the process of converting a hexadecimal number to its decimal equivalent, in particular when converting each hexadecimal digit to its decimal value.

Say when the digit i of hexVal equals any characters ranging from '0' to '9', its decVal equals the hexVal subtracted by 48 and then timed by the digitBase:

if ((hexVal[i] >= '0') && (hexVal[i] <= '9')) {
    decVal += (hexVal[i] - 48) * digitBase;
    ...
}

I understand that 48 is ASCII value of '0'. What I am in doubt with is where the values 55 and 87 come from when digit i of hexVal equals the ranges 'A' to 'F' and 'a' to 'f':

else if ((hexVal[i] >= 'A') && (hexVal[i] <= 'F')) {
    hexToDec += (hexVal[i] - 55) * digitBase;
    ...
}

and

else if ((hexVal[i] >= 'a') && (hexVal[i] <= 'f')) {
    hexToDec += (hexVal[i] - 87) * digitBase;
    ...
}

The code blocks above are extracted from the following function which works well to convert hexadecimal numbers to their equivalent decimals.

int conv_hex_to_dec(char hexVal[]) {

    int hexToDec = 0;
    int len = strlen(hexVal);
    int digitBase = 1; 

    // Extract hex characters as digits from last character
    for (int i = len - 1; i >= 0; i--) {

        if ((hexVal[i] >= '0') && (hexVal[i] <= '9')) {
            hexToDec += (hexVal[i] - 48) * digitBase;
            digitBase = digitBase * 16;
        }

        else if ((hexVal[i] >= 'A') && (hexVal[i] <= 'F')) {
            hexToDec += (hexVal[i] - 55) * digitBase; 
            digitBase = digitBase * 16;
        }
        else if ((hexVal[i] >= 'a') && (hexVal[i] <= 'f')) {
            hexToDec += (hexVal[i] - 87) * digitBase; 
            digitBase = digitBase * 16;
        }
        else {
            printf("Invalid hex val");
        }
    }

    return hexToDec;
}

Any explanation will be much appreciated.

Thanks.


Solution

48 is the ASCII code for '0'; the ASCII codes for 'A' and 'a' are 65 (55 = 65-10) and 97 (87 = 97 - 10) respectively.



Answered By - Scott Hunter
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to access the decimal numbers which are not stored in float value

 August 10, 2022     decimal, numbers, python     No comments   

Issue

If I want to access the 100th decimal of the number 1/919, is there a way to do so? I know that floating values are stored only upto certain decimals so I can access only the decimals which are stored but how to access the decimals which are not stored


Solution

Your intuition is correct. Python stores floats as 64-bit floating point values, which don't have the precision to go out to 100 decimals. You will have to use the decimal package and set the precision to what you need.

import decimal

# calculate up to 120 decimals
decimal.get_context().prec = 120

result = decimal.Decimal(1) / decimal.Decimal(919)
print(result)


# pull an arbitrary digit out of the string representation of the result
def get_decimal_digit(num, index):
    # find where the decimal points start
    point = str(num).rfind('.')
    return int(str(num)[index + point + 1])

# get the 100th decimal
print(get_decimal_digit(result, 100))


Answered By - dogman288
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, August 9, 2022

[FIXED] How can I format a String number to have commas and round?

 August 09, 2022     decimal, java, number-formatting, numbers, string     No comments   

Issue

What is the best way to format the following number that is given to me as a String?

String number = "1000500000.574" //assume my value will always be a String

I want this to be a String with the value: 1,000,500,000.57

How can I format it as such?


Solution

You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).

You also need to convert that string into a number, this can be done with:

double amount = Double.parseDouble(number);

Code sample:

String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");

System.out.println(formatter.format(amount));


Answered By - NullUserException
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to find an integer multiplier to get to a power of 10?

 August 09, 2022     decimal, math, numbers     No comments   

Issue

I'm trying to create an exact decimal numeric type. I was storing it as a rational p/q where q is always as power of 10.

Now if I try to divide one of these numbers, I need to see if the result is representable as a finite decimal expansion. For example 10.2 / 80 => 0.1275 is okay, but 10 / 3 = 3.333... is not okay.

It boils down to looking at an integer q and asking: is there an integer m such that:

q * m = 10 ^ n    (q, m, n are all integers)

I can write a loop to search for it, testing n=0,1,2,3,...? But is there a more direct way? I don't know how to solve that little equation algebraiclly.


Solution

First, you need to see whether q can be written as the product of 2s and 5s; if it can, there will be an integer solution for m and n. Otherwise, there will not be.

We can find integers a, b and c such that q = (2^a)(5^b)c and c is not divisible by 2 or 5. Do this by repeatedly dividing q by 2 as long as q is still divisible by 2, incrementing a each time; then, divide by 5 and increment b as long as q is still divisible by 5; then, c will be whatever the value of q remains after this process of dividing by 2 and 5 repeatedly.

At this point, if c = 1, we can find a solution; otherwise, there is no integer m that works. Assuming c = 1, check a and b:

  • if a = b, q was a power of 10 already; choose m = 1
  • if a < b, choose m = 2^(b-a)
  • if a > b, choose m = 5^(a-b)


Answered By - Patrick87
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make 2 decimals place in javaScript

 August 09, 2022     decimal, javascript, numbers     No comments   

Issue

I need to show 2 decimals place after the total amount of payment.

I have tried this way:

  cart.itemsPrice = cart.cartItems.reduce(
    (acc, item) => acc + (item.price * item.qty).toFixed(2),
    0
  );

then output show me like this:

$0269.97179.9888.99

I don't konw why,

then If I try to like this:

 cart.itemsPrice = cart.cartItems.reduce(
    (acc, item) => acc + Math.round(item.price * item.qty).toFixed(2),
    0
  );

then still I got the same garbage value

Any Suggestion please.


Solution

Ok, toFixed returns a string (see docs). So when you are trying to add a number to a string, it just converts the number to a string and adds two strings. You can convert back value to number by using "+" operator acc + +value.toFixed(2);

So it would be better to perform toFixed method on the result of your reduce function. Math.round should also work for you (Math.round(value*100)/100) (see docs).

console.log((3.033333).toFixed(2) + 4.5) // will print 3.034.5 

cart.itemsPrice = (cart.cartItems.reduce(
  (acc, item) => acc + (item.price * item.qty),
  0
)).toFixed(2);


Answered By - Dmytro Krasnikov
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why did I get an exception "Cannot implicitly convert type 'bool' to 'long?'" when using the LINQ Sum method and how to fix it?

 August 09, 2022     c#, decimal, linq, numbers, sum     No comments   

Issue

I have the following code which is working:

IEnumerable<Decimal?> values = getValues();

var sum = values.Where(x => x > 0).Sum();

But if I try:

var sum = values.Sum(x => x > 0);

I get the error:

Cannot implicitly convert type 'bool' to 'long?'

Shouldn't this work either applying the filter in Sum or Where?


Solution

Indeed, Sum requires numbers values and not boolean evaluation results.

You need first to filter using Where or Select (not relevant here) then Sum:

var sum = values.Where(x => x != null && x > 0).Sum();

I added the null check because the collection is type of decimal?.

Else you need to write that but this is less speed optimized:

var sum = values.Sum(x => x != null && x > 0 ? x : 0);

Using a selector for Sum is for example usefull when having classes, structs or tuples:

var sum = controls.Sum(control => control.Width);


Answered By - user12031933
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 8, 2022

[FIXED] How to control the number of decimals places for display purpose only using Image function in Ada?

 August 08, 2022     ada, decimal, display, numbers     No comments   

Issue

I have the following code line in Ada,

     Put_Line ("Array of " & Integer'Image (iterations)
        & "          is " & Long_Float'Image (sum) 
        & " Time = " & Duration'Image(milliS) & timescale);  

The number of decimal places in sum is too long for display (not for calculations since long float is needed for sum calculations). I know that Ada has alternative way of displaying decimals using aft and fore without using the Image function but before I switch to alternative I would like to know if Image has options or other technique of displaying decimals. Does Image function has an option to display decimals? Is there a technique to shorten the number of decimal places of the Long_Float for display only?

with Ada.Numerics;
 with Ada.Text_IO; use Ada.Text_IO;

 procedure Images is
 sum                : Standard.Long_Float;
 Pi                 : Long_Float := Ada.Numerics.Pi;

  type Fixed is delta 0.001 range -1.0e6 .. 1.0e6;
  type NewFixed is range -(2 ** 31) .. +(2 ** 31 - 1);
  type Fixed2 is new Long_Float range -1.0e99.. 1.0e99;
  type Fixed3 is new Long_Float range -(2.0e99) .. +(2.0e99);


 begin
 sum:=4.99999950000e14;
 Put_Line ("no fixing number: " & Pi'Image);
 Put_Line (" fixed number: " & Fixed'Image(Fixed (Pi)));
 Put_Line ("no fixing number: " & Long_Float'Image(sum));
 Put_Line (" testing fix: " & Fixed3'Image(Fixed3 (sum)));
 end Images;

Addendum:

  1. Note that my variable sum is defined as Standard.Long_Float to agree with other variables used throughout the program.
  2. I am adding code to show the culprit of my problem and my attempts at solving the problem. It is based on example provided by Simon Wright with sum number added by me. Looks like all I need to figure out how to insert delta into Fixed3 type since delta defines number of decimals.

Solution

’Image doesn’t have any options, see ARM2012 3.5(35) (also (55.4)).

However, Ada 202x ARM K.2(88) and 4.10(13) suggest an alternative:

with Ada.Numerics;
with Ada.Text_IO; use Ada.Text_IO;
procedure Images is
   Pi : Long_Float := Ada.Numerics.Pi;
   type Fixed is delta 0.001 range -1.0e6 .. 1.0e6;
begin
   Put_Line (Pi'Image);
   Put_Line (Fixed (Pi)'Image);
end Images;

which reports (GNAT CE 2020, FSF GCC 10.1.0)

$ ./images 
 3.14159265358979E+00
 3.142


Answered By - Simon Wright
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, August 7, 2022

[FIXED] How can I keep the trailing zereos with .3g?

 August 07, 2022     decimal, numbers, python, significant-digits     No comments   

Issue

I have the following value: 6.095651174e-09 and I am printing it like this:

print(f' the result is: {forces[index]: .3g} N') 

Here the output is 6.1e-09 but I want to keep the zero after it was rounded from 6.09 to 6.1. My desired output would be: 6.10

A normal float works with this. But with g it does not work anymore. I want to keep the E at the end and therefore I want to stay with g (and not f).

Is it possible to have 6.10e-09 printed out here? I only found things for float and those solutions did not work with my case.

Thanks for every help!


Solution

I don't have the issue with the e type:

i = 6.0956e-9
print(f'result: {i: .2e} N')

Output:

result:  6.10e-09 N


Answered By - mozway
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to convert latin numbers to arabic in javascript?

 August 07, 2022     decimal, javascript, number-formatting, numbers, reactjs     No comments   

Issue

I use a custom function to convert numbers to arabic format like this :

 const numbers = `۰۱۲۳۴۵۶۷۸۹`;
  const convert = (num) => {
    let res = "";
    const str = num.toString();
    for (let c of str) {
      res += numbers.charAt(c);
    }
    return res;
  };

And it works like this :

console.log(convert(123)) // ==> ۱۲۳

The problem occurs when there is a number with decimals and it converts it to arabic format without the decimal dots for example :

console.log(convert(123.9)) // ==> ۱۲۳۹

I expect the output to be ۱۲۳،۹ .

How can I convert numbers with decimals to arabic format with decimal dots included with my function ?


Solution

Try toLocaleString()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

console.log((123.9).toLocaleString('ar-AE'))

Edit:

with toLocaleString options

(123.9872512).toLocaleString("ar-AE", {
  useGrouping: false,
  maximumSignificantDigits: 10
})


Answered By - User863
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing