PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 9, 2022

[FIXED] How can I convert a string such as 5.7303333333e+02 to decimal in PowerShell?

 August 09, 2022     data-conversion, decimal, powershell     No comments   

Issue

I'm trying to convert strings such as 5.7303333333e+02 to the decimal type. I've tried using [decimal]::TryParse but the return value is false.

Is there a method similar to [datetime]::parseexact, or any clean way to convert these strings? Or am I going to have to parse out the e+02 and do that math separately?


Solution

What about :

[int]"5.7303333333e+02"
[decimal]"5.7303333333e+02"


Answered By - JPBlanc
Answer Checked By - Mildred Charles (PHPFixing Admin)
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 format a number to show at least n decimals

 August 09, 2022     abap, decimal, string     No comments   

Issue

Is there a simple way to format a number to show at least n decimals ? If possible, using string templates and avoiding processing the string with code.

Expected results for 2 wanted decimals:

Value (type f) Expected output
4 4.00
0.4 0.40
0.04 0.04
0.004 0.004
0.0004 0.0004

I've only found ways to specify fixed decimal precision through string templates.


Solution

I'm not quite sure this can be achieved with string templates alone, as your requirements are quite special. However if you specify the number of decimals in the string template, the trailing zeros can be cut off with a regex:

DATA numbers TYPE STANDARD TABLE OF f.
numbers = VALUE #(
  ( 4 / 1     )
  ( 4 / 10    )
  ( 4 / 100   )
  ( 4 / 1000  )
  ( 4 / 10000 )
).

LOOP AT numbers INTO DATA(number).
  DATA(formatted) = replace(
    val = |{ number DECIMALS = 4 }|
    regex = '0{1,2}\z'
    with = ''
  ).

  WRITE formatted. NEW-LINE.
ENDLOOP.

Some comments:

  • The \z operator matches the end of a string
  • DECIMALS = 4 was an arbitrary choice based on the examples, you might want to choose a larger number there, and then adapt the regex to match 0{1, N - 2} zeros.
  • In a very new system you might want to have a look at the new PCRE


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

[FIXED] How can I initialize Decimal without losing precision in Swift

 August 09, 2022     decimal, swift     No comments   

Issue

let decimalA: Decimal = 3.24
let decimalB: Double = 3.24
let decimalC: Decimal = 3.0 + 0.2 + 0.04
print (decimalA)    // Prints 3.240000000000000512
print (decimalB)    // Prints 3.24
print (decimalC)    // Prints 3.24

I'm totally confused. Why do these things happen? I know why floating point numbers lose precision, but I can't understand why Decimal lose precision while storing decimal numbers.

I want to know how can I initialize Decimal type without losing precision. The reason why these happen is also very helpful to me. Sorry for my poor English.


Solution

The problem is that all floating point literals are inferred to have type Double, which results in a loss of precision. Unfortunately Swift can't initialise floating point literals to Decimal directly.

If you want to keep precision, you need to initialise Decimal from a String literal rather than a floating point literal.

let decimalA = Decimal(string: "3.24")!
let double = 3.24
let decimalC: Decimal = 3.0 + 0.2 + 0.04
print(decimalA) // Prints 3.24
print(double) // Prints 3.24
print(decimalC) // Prints 3.24

Bear in mind this issue only happens with floating point literals, so if your floating point numbers are generated/parsed in runtime (such as reading from a file or parsing JSON), you shouldn't face the precision loss issue.



Answered By - Dávid Pásztor
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to convert string to decimal in powershell?

 August 09, 2022     data-conversion, decimal, powershell     No comments   

Issue

I have a string,

$string = "2,55"

How to convert this string to decimal?


Solution

In short -

[decimal]$string.Replace(",", ".")


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

[FIXED] How to add two columns of a dataframe as Decimals?

 August 09, 2022     decimal, pandas, python     No comments   

Issue

I am trying to add two columns together using the Decimal module in Python but can't seem to get the syntax right for this. I have 2 columns called month1 and month2 and do not want these to become floats at any point in the outcome as division and then rounding will later be required.

The month1 and month2 columns are already to several decimals as they are averages and I need to preserve this accuracy in the addition.

I can see guidance online for how to add numbers together using Decimal but not how to apply it to columns in a pandas dataframe. I've tried things like:

df['MonthTotal'] = Decimal.decimal(df['Month1']) + Decimal.decimal(df['Month1'])

What is the solution?


Solution

from decimal import Decimal

def convert_decimal(row):
    row["monthtotal"] = Decimal(row["month1"])+Decimal(row["month2"])
    return row

df = df.apply(convert_decimal, axis =1)


Answered By - Rishin Rahim
Answer Checked By - Mildred Charles (PHPFixing Admin)
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] How to check if a number has a decimal place/is a whole number?

 August 09, 2022     decimal, floating-point, java, java-8     No comments   

Issue

My input field BigDecimal num may contain both integer and floating numbers.

num = 45
or 
num = 45.5343434

If the BigDecimal input field num contains decimal places, then I would like to limit the decimal places to 4.

Desired Output : 45.5343 if input num = 45.5343434
Desired Output : 45 if input num=45

How can I do that?


Solution

You are interested in what is called the scale of your BigDecimal.

Call BigDecimal#scale.

BigDecimal x = new BigDecimal( "45.5343434" );
BigDecimal y = new BigDecimal( "45" );

x.scale(): 7

y.scale(): 0

You asked:

I would like to limit the decimal places by 4

Test for the scale being larger than four. If so, round.

    BigDecimal num = new BigDecimal(45);
    if (num.scale() > 4) {
        num = num.setScale(4, RoundingMode.HALF_UP);
    }
    System.out.println(num);

Output:

45

In case of more decimals:

    BigDecimal num = new BigDecimal("45.5343434");

45.5343

You can choose a different rounding mode to fit with your requirements.



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

[FIXED] How to generate random Decimal128, Decimal256 numbers with Python

 August 09, 2022     clickhouse, decimal, python, random     No comments   

Issue

I am making a test for ClickHouse database for verifying Decimal data types. According to documentation:

Decimal Parameters:

P - precision. Valid range: [1 : 76]. Determines how many decimal digits number can have (including fraction). S - scale. Valid range: [0 : P]. Determines how many decimal digits fraction can have. Depending on P parameter value Decimal(P, S) is a synonym for:

  • P from [1 : 9] - for Decimal32(S)
  • P from [10 : 18] - for Decimal64(S)
  • P from [19 : 38] - for Decimal128(S)
  • P from [39 : 76] - for Decimal256(S)

I am trying to generate random numbers for all of these data types. I've found a good answer already and this is how I used it:

Decimal32:

>>> decimal.Decimal(random.randint(-2147483648, 2147483647))/1000
Decimal('-47484.47')

Decimal64:

>>> decimal.Decimal(random.randint(-9223372036854775808, 9223372036854775807))/100000000000
Decimal('-62028733.96730274309')

These two give me the expected result. But, my function for Decimal128 already is too long and produces wrong result:

>>> decimal.Decimal(random.randint(-170141183460469231731687303715884105728, 170141183460469231731687303715884105727))/1000000000000000000000
Decimal('149971182339396169.8957534906')

Question:

How can I generate random Decimal128 and Decimal256?

Please suggest what I should use.


Solution

The problem you face, is that the precisison is not set high enough to record all the digits in your division. The simplest way to fix it, is to increase the precision (at the expense of the division and all other operations taking longer to execute. The default precision is set to 28, that is 28 correct fractional digits. This is enough for Decimal64, but too few for Decimal128 and Decimal256

To update the precision you write:

decimal.getcontext().prec = 38 # Maximum number of fractional digits in Decimal128

After this your code should work. Of course, for Decimal256, the precision needs to be set to 76.



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

[FIXED] How should I handle decimal in SQLalchemy & SQLite

 August 09, 2022     decimal, sqlalchemy, sqlite, type-conversion     No comments   

Issue

SQLalchemy gives me the following warning when I use a Numeric column with an SQLite database engine.

SAWarning: Dialect sqlite+pysqlite does not support Decimal objects natively

I'm trying to figure out the best way to have pkgPrice = Column(Numeric(12,2)) in SQLalchemy while still using SQLite.

This question [1] How to convert Python decimal to SQLite numeric? shows a way to use sqlite3.register_adapter(D, adapt_decimal) to have SQLite receive and return Decimal, but store Strings, but I don't know how to dig into the SQLAlchemy core to do this yet. Type Decorators look like the right approach but I don't grok them yet.

Does anyone have a SQLAlchemy Type Decorator Recipe that will have Numeric or Decimal numbers in the SQLAlchemy model, but store them as strings in SQLite?


Solution

from decimal import Decimal as D
import sqlalchemy.types as types

class SqliteNumeric(types.TypeDecorator):
    impl = types.String
    def load_dialect_impl(self, dialect):
        return dialect.type_descriptor(types.VARCHAR(100))
    def process_bind_param(self, value, dialect):
        return str(value)
    def process_result_value(self, value, dialect):
        return D(value)

# can overwrite the imported type name
# @note: the TypeDecorator does not guarantie the scale and precision.
# you can do this with separate checks
Numeric = SqliteNumeric
class T(Base):
    __tablename__ = 't'
    id = Column(Integer, primary_key=True, nullable=False, unique=True)
    value = Column(Numeric(12, 2), nullable=False)
    #value = Column(SqliteNumeric(12, 2), nullable=False)

    def __init__(self, value):
        self.value = value


Answered By - van
Answer Checked By - Katrina (PHPFixing Volunteer)
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

[FIXED] How to truncate decimals to x places in Swift

 August 09, 2022     decimal, double, ios, swift     No comments   

Issue

I have a really long decimal number (say 17.9384693864596069567) and I want to truncate the decimal to a few decimal places (so I want the output to be 17.9384). I do not want to round the number to 17.9385.

How can I do this?


Solution

You can tidy this up even more by making it an extension of Double:

extension Double {
    func truncate(places : Int)-> Double {
        return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
    }
}

You use it like this:

var num = 1.23456789
// return the number truncated to 2 places
print(num.truncate(places: 2))

// return the number truncated to 6 places
print(num.truncate(places: 6))


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

[FIXED] How to keep extra decimals in Python

 August 09, 2022     decimal, python     No comments   

Issue

I want to add a number to a numpy array and I would like to keep all the decimals. How can I do it? This is what I tried so far:

import numpy as np
a = np.array([0.25350021,  0.16900018, -0.16899996])
b = 1.05292844e-07
np.around(a+b,decimals=15)

The output is array([ 0.25350032, 0.16900029, -0.16899985]), but b has non-zero digits up to 10^-15 and I would like them to appear explicitly in the numpy array. Thank you!


Solution

I don't know why it is not keeping the 15 digits, however, here is a solution that I came up with to get the answer that you want.

import numpy as np

def addNumberToArray(array, number):
    newArray = []
    for element in array:
        element = element + number
        newArray.append(element)
    return newArray


a = np.array([0.25350021,  0.16900018, -0.16899996])
b = 1.05292844e-07
result = addNumberToArray(a, b)
print (result)

Output: [0.253500315292844, 0.169000285292844, -0.168999854707156]



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

[FIXED] How to move Collection<Double> values greater than 0 to decimal places

 August 09, 2022     collections, decimal, double, hashmap, java     No comments   

Issue

I want to move every value greater than 0 to one decimal place for Collection<Double>, how would I do that?

Where single units are moved 3 decimal places, tens are moved 2 decimal places and hundreds are moved 1 decimal place.

For example:

//an array like this
[140, 23, 3]

//should be
[0.140, 0.023, 0.003]

The script I am using counts the amount of times a particular String appears, though I'm unsure how to approach the above with Collection<Double>:

public class doubleTest {

HashMap<String, Double> texted(String tex) {
        

        HashMap<String, Double> counts = new HashMap<String, Double>();

        for (String word : tex.split(" ")) { // loops through each word of the string
            // text.split(" ") returns an array, with all the parts of the string between your regexes
            // if current word is not already in the map, add it to the map.

            if (!counts.containsKey(word)) counts.put(word, (double) 0);

            counts.put(word,counts.get(word) + 1); // adds one to the count of the current word

        }
return counts;
    }

}

    public static void main(String[] args) {
        
        final   String text = "Win Win Win Win Draw Draw Loss Loss";
        
        textSplit countWords = new textSplit();
        
        HashMap<String, Double> result = countWords.texted(text);
        

       Collection<Double> resultD = result.values();

      for(int i = 0; i<resultD.size();i++){
            double[] value = new double[]{i*0.001};
Collection<Double> valuet = Arrays.stream(value).boxed().collect(Collectors.toCollection(ArrayList::new));

        System.out.println(valuet);

//output
//[0.0]
//[0.001]
//[0.002]

     
      
  
                   }


        //System.out.println(resultD);
        
        
    }
    
}

Solution

The simpler way of doing this is using the map() function.

Logic:- Multipy each element of array with 0.001

public class Test2 {
 public static void main(String[] args) {
     
     List<Integer> list = Arrays.asList(140,23,3);
     Collection<Double> collection;
     collection = list.stream().map(x ->  x* .001).collect(Collectors.toCollection(ArrayList::new));
     System.out.println(collection);
 }
}

Output

[0.14, 0.023, 0.003]



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

[FIXED] How to manually convert Hexadecimal to Decimal in C#?

 August 09, 2022     c#, command-line, decimal, hex     No comments   

Issue

So we were asked to convert a Hexadecimal Value (stored in a String) to its Decimal Value. Each character in the String should be manually converted to decimal within a loop, and then post the total Decimal Value of the Hexadecimal Value. I got here the codes that I have written but I couldn't identify where I could have gone wrong for an "F4" Hexa (as an example) to have a Decimal Equivalent of "292" instead of "244". I have debugged everything, the code seems fine. Any ideas?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvProgCS
{
    class Program
    {
        static int dec=0;
        static string hex;
        static void Main(string[] args)
        {
            do{
                Console.Write("[Press 0 to Stop] Hexadecimal Value: ");

                hex = Console.ReadLine();
                if (hex == "0") break;
                int length = hex.Length;
                for (int i = 0; i < length+1; i++)
                {

                    if (hex[i] == 'A' || hex[i] == 'B' || hex[i] == 'C' || hex[i] == 'D' || hex[i] == 'E' || hex[i] == 'F')
                    {
                        if (hex[i] == 'A')
                            dec+= 10 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'B')
                            dec += 11 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'C')
                            dec += 12 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'D')
                            dec += 13 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'E')
                            dec += 14 * Convert.ToInt32(Math.Pow(16, length - 1));
                        if (hex[i] == 'F')
                            dec += 15 * (Convert.ToInt32(Math.Pow(16, length - 1)));
                    }
                    else
                        dec += hex[i];
                    length--;
                }
                Console.WriteLine("DECIMAL EQUIVALENT: " + dec + "\n");
            }
            while(hex != "0");

        }
    }
}

Solution

You forgot about the Math.Pow in the dec += hex[i] line where you also have to convert hex[i] from char into a number.

dec += (int)char.GetNumericValue(hex[i]) * (int)Math.Pow(16, length - 1);

Moreover, as observed by Partha:

Also add dec = 0; after your print statement. I think the dec values are getting adding to itself for each iteration.



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

[FIXED] How to convert 10^4 to binary

 August 09, 2022     binary, computer-science, decimal, math     No comments   

Issue

I need to convert 10^4 to binary

expanding it will give me a large number and dividing that by 2 a bunch of times will be really inefficient

10^4 = 10000

how do i do it directly


Solution

I would write a recursive function, the pseudo-code is here:

int Convert_to_binary (x):
     if(x == 0):
        return 1;
     if(x == 1):
        return 10;
     if(x%2 == 1):
        return Convert_to_binary(x-1)+1;
     if(x%2 == 0):
        return Convert_to_binary(x/2)*10;

This will return the binary format as an integer like 2 is 10 in binary and 1 is 1 in binary format and 3 is 11 and so on



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

[FIXED] Why a decimal value from MySQL is converted into/shown as integer?

 August 09, 2022     decimal, laravel, mysql, php     No comments   

Issue

My database includes a table named Quotations. This table has a column named Cost with a datatype decimal (10, 2). Values are saved/updated as per my expectation inside the column just like (25.75, 4.35, 10.38 etc).

Problem is that whenever I use {{ $quotation->cost }} to display the information, all the decimals are printed as integers like (25, 4, 10). But if I check it with {{ dd($quotation) }}, it shows all the exact decimal values like (25.75, 4.35, 10.38 etc).

I shall appreciate it if someone points out the root cause of the problem.


Solution

Problem solved. I thank everybody for your timely responses.

Before the solution, I actually was ignoring protected $casts = [ 'cost' => 'integer' ]. Replacing integer to float resolved my issue.



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

[FIXED] How to display 3 decimal points without round up?

 August 09, 2022     android, bigdecimal, decimal, java, number-formatting     No comments   

Issue

I am making an app which need to display 3 decimal points i achieve this by NumberDecimal but the issue is if 4th digit is >5 then 3rd digit automatically increase. I want to show exact figure for ex :

Result           : 100.2356 
Output           : 100.236  // Applying NumberDecimal

Need this output : 100.235 // I need this output

This is my function :
public String setdecimal(float a) 
{
   NumberFormat formatter = new DecimalFormat("##.###");
   return formatter.format(a);

}

Solution

Use RoundingMode.FLOOR:

NumberFormat formatter = new DecimalFormat("##.###");
formatter.setRoundingMode(RoundingMode.FLOOR);

Depending on how you want to handle negative numbers, you could also use RoundingMode.DOWN, which rounds towards zero.



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

[FIXED] How to Format decimal in C# and keep ending 0?

 August 09, 2022     c#, decimal, format     No comments   

Issue

In C# how can I format $2,471,450.5 to $2,471,450.50 (Keeping Zero at the end)

This is the expression I'm using to format it and get this value $2,471,450.5 But I've trouble to display like this $2,471,450.50

String.Format(culture, "{0:$#,#.##;($#,#.##)}", rdr.GetDecimal(10))

Solution

This is the correct expression. Changed # to 0. Thank you for your help.

String.Format(culture, "{0:$#,#.00;($#,#.##)}", rdr.GetDecimal(10))


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

[FIXED] How to pass a decimal value when making a post request in django?

 August 09, 2022     decimal, django, django-rest-framework, json, python-3.x     No comments   

Issue

I am trying to make a post request to a third party application along with some data and the data also have a decimal value up to two points, which I am getting from database (order.amount) but after making the request getting error saying data is not serializable to json then i passed it as '"%s"' % round(order.amount,2) then also getting error post data is empty.Looking for suggestion to solve this problem.

    request = Transfer.request_transfer(beneId=beneficiary_id, amount=round((order.amount),2) 
    transferId=transfer_identifier,remarks="Test transfer")

    getting error: decimal is not json serializable

    print('"%s"' % round((order.amount),2) #"5000.23"
    
    request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")
    
    getting error : PreconditionFailedError: Reason = Post data is empty or not a valid JSON:: response = {"status": "ERROR", "subCode": "412", "message": "Post data is empty or not a valid JSON"}
    
    
    but when hardcoding amount then it is working
    request = Transfer.request_transfer(beneId=beneficiary_id, amount= "5000.23" transferId=transfer_identifier,remarks="Test transfer")

Solution

Pay attention to this line,

print('"%s"' % round((order.amount),2) #"5000.23"

I guess you miss one thing: you're formatting your decimal value, but you do this with quotes, so your variable amount will contain "5000.23" string instead of 5000.23.

So, look:

request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")

you have amount='"5000.23"' and these quotes get in the way of serialization.

To fix it, just remove the additional quotes:

print('%s' % round((order.amount),2) # '5000.23'

request = Transfer.request_transfer(beneId=beneficiary_id, amount='%s' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")


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

[FIXED] How to evaluate if a number is cube

 August 09, 2022     c#, decimal, double, integer, math     No comments   

Issue

I'm trying to calculate the cube root of a number to check if it's a perfect cube. Unfortunately the .NET Framework has no built-in function for that. So in order to calculate the cube root of a number I have to use the Math.Pow function:

double cubeRoot = Math.Pow(125, (double)1 / 3);

When I try to evaluate if the cube root is an integer it outputs false, yet 125 is a perfect cube:

Console.WriteLine(cubeRoot % 1 == 0);

How can I overcome this issue?


Solution

You need to round and check if the cube of the cube root is equal to the original value

double input = 125;
double cubeRoot = Math.Pow(input, 1.0/3.0);
double c = Math.Round(cubeRoot);
Console.WriteLine(c*c*c == input);

Note that Math.Pow(input, 1.0/3.0) is not the most accurate way to calculate cube root because 1.0/3.0 is not exactly representable in binary (and decimal). But since we're rounding the result to int anyway, the output will not be affected

.NET Core 2.1 added Math.Cbrt(double) which can be used to get a correct result in double precision, though I'm not sure if it's faster than the Math.Pow() solution or not



Answered By - phuclv
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to limit my decimal value to 2 places on my <td>

 August 09, 2022     decimal, html-table, javascript, jquery     No comments   

Issue

I'm making a query to my database to return a value of double precision. This value in my database goes up to 17 decimal places but I only want to display 2 decimal places on the web page.

This is my html with the table. The value of the decimal goes into the {{savings_percent}}

 <table class="table text-light text-end">
                                        <thead>
                                            <tr>
                                                
                                                <th scope="col">CHW</th>
                                       
                                            </tr>
                                        </thead>
                                        <tbody class="text-end">
                                            <tr id="decimal">
                                                <th scope="row">%</th>
                                                {{#with chw}}
                                                <td class='rounded'>{{savings_percent}}</td>
                                                {{/with}}
                                            
                                        </tbody>
                                    </table>

This is how I'm trying to grab the value, convert it to decimal and then give it a fixed number of two decimals. The console is giving me $(...).val(...).toFixed is not a function. Does anyone have a solution on how I can fix this?

let decimal = parseFloat($("#decimal .rounded").text())
    
    window.onload = () => {

        $('.rounded').val(decimal).toFixed(2)

        console.log(decimal)   
    };

Solution

val() is only for form controls

I would use text(function) which gives you the current text to do what you need to before returning modifications

$('.rounded').text(function(i,curr){
    return parseFloat(curr).toFixed(2)
})


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

[FIXED] How to limit my decimal value to 2 places on my <td>

 August 09, 2022     decimal, html-table, javascript, jquery     No comments   

Issue

I'm making a query to my database to return a value of double precision. This value in my database goes up to 17 decimal places but I only want to display 2 decimal places on the web page.

This is my html with the table. The value of the decimal goes into the {{savings_percent}}

 <table class="table text-light text-end">
                                        <thead>
                                            <tr>
                                                
                                                <th scope="col">CHW</th>
                                       
                                            </tr>
                                        </thead>
                                        <tbody class="text-end">
                                            <tr id="decimal">
                                                <th scope="row">%</th>
                                                {{#with chw}}
                                                <td class='rounded'>{{savings_percent}}</td>
                                                {{/with}}
                                            
                                        </tbody>
                                    </table>

This is how I'm trying to grab the value, convert it to decimal and then give it a fixed number of two decimals. The console is giving me $(...).val(...).toFixed is not a function. Does anyone have a solution on how I can fix this?

let decimal = parseFloat($("#decimal .rounded").text())
    
    window.onload = () => {

        $('.rounded').val(decimal).toFixed(2)

        console.log(decimal)   
    };

Solution

val() is only for form controls

I would use text(function) which gives you the current text to do what you need to before returning modifications

$('.rounded').text(function(i,curr){
    return parseFloat(curr).toFixed(2)
})


Answered By - charlietfl
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What are the parameters for the number Pipe - Angular 2

 August 09, 2022     angular, decimal, pipe     No comments   

Issue

I have used the number pipe below to limit numbers to two decimal places.

{{ exampleNumber | number : '1.2-2' }}

I was wondering what the logic behind '1.2-2' was? I have played around with these trying to achieve a pipe which filters to zero decimal places but to no avail.


Solution

The parameter has this syntax:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

So your example of '1.2-2' means:

  • A minimum of 1 digit will be shown before decimal point
  • It will show at least 2 digits after decimal point
  • But not more than 2 digits


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

[FIXED] Why are only the first 2 outputs correct in my binary to decimal converter programm?

 August 09, 2022     binary, c, decimal     No comments   

Issue

I have to program a converter which takes the strings from numbers[] and outputs them as decimals.

I am looping through size and index to then add up the current index to the power of its position and then sum it all up. Like: 101 = 1^2 + 0^1 + 1^0

So I am currently stuck with this:

#include <stdio.h>

#include <math.h> // Kompilieren mit -lm : gcc -Wall -std=c11 dateiname.c -lm

int main() {
    char* numbers[] = {
        "01001001",
        "00101010",
        "010100111001",
        "011111110100101010010111",
        "0001010110011010101111101111010101110110",
        "01011100110000001101"};
    
    // Add here..

int strlen(char *str){
int len=0;
for(;str[len]!='\0';len++){}
return len;
}

int sum = 0;
int length = sizeof(numbers) / sizeof(numbers[0]);

for( int i = 0; i < length; i++ ){
    
     int size = strlen(numbers[i]);
     
    for (int j = 0; j < size; j++) {
     
        if(numbers[i][j] == '1'){ 
            sum += 1 * pow(2,j-1);
        }else{
            sum += 0 * pow(2,j-1);
        }
    }
       printf("%s to the base of 2 \nequals %d  to the base of 10 \n\n",numbers[i], sum); 
       sum = 0;
       
    }
            
    return 0;
}

The output of the first two loops is correct which is 01001001 = 73 and 00101010 = 42. But, as soon the length get bigger, my output is completely wrong; e.g. 010100111001 = 1253 instead of 1337 and 011111110100101010010111 = 7645567 instead of 8342167.


Solution

There are a number of issues with your code. First and foremost, as pointed out in the comments, you are processing your binary digits from left-to-right, whereas you should be doing that right-to-left.

Second, declaring a function inside another one (as you have done for your strlen) is not Standard C (though some compilers may allow it). If you really can't use the standard strlen function (provided in <string.h>), then move your definition to outside (and before) the body of main.

Third, you shouldn't be using the pow function (which takes and returns double values) for integer arithmetic. Just use a running int variable and multiply that by two each time the inner for loop runs.

Fourth, your "0001010110011010101111101111010101110110" value will overflow the int type on most machines (assuming that is 32 bits), so try using long long int (most likely 64 bits) where necessary.

Finally, there's no point in adding 0 * x to anything, whatever x is, so you can do away with the else block.

Here's a working version (using the standard strlen):

#include <stdio.h>
#include <string.h> // For "strlen" - we don't need math.h if we don't use "pow".

int main(void) // For strict compliance, you should add the "void" argument list
{
    char* numbers[] = {
        "01001001",
        "00101010",
        "010100111001",
        "011111110100101010010111",
        "0001010110011010101111101111010101110110",
        "01011100110000001101" };

    long long int sum = 0; // So we can use more than 32 bits!
    size_t length = sizeof(numbers) / sizeof(numbers[0]);
    for (size_t i = 0; i < length; i++) {
        int size = (int)strlen(numbers[i]); // strlen gives a "size_t" type
        long long int p = 1;
        for (int j = size-1; j >= 0; j--) { // Start at the END of the string and work backwards!
            if (numbers[i][j] == '1') {
                sum += p;
            }
            // No point in adding zero times anything!
            p *= 2; // Times by two each time through the loop
        }
        printf("%s to the base of 2 \nequals %lld  to the base of 10 \n\n", numbers[i], sum);
        sum = 0;

    }
    return 0;
}


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

[FIXED] How to set decimal places in plotly subplots hoverlabel?

 August 09, 2022     decimal, hover, plotly, precision     No comments   

Issue

I would be very happy if someone could help me with this: I created a loop using pandas and plotly express which creates n stacked subplots from a tuple of dataframes selected by the user.

The source data has 10 decimal places, so I set

    pd.set_option('precision',10)

The dataframes show adequate decimal precision, the scatter plots work, but I cannot get the hover label to show all 10 decimal places. I tried to set

    fig.update_layout(hoverlabel_namelength=-1)

but it only changes the X-Axis reference in the hoverlabel, not the Y-Axis (containing the numbers).

Can anyone help me?

Thank you very much in advance!! Maria

Here is my source program:

#import libraries

import tkinter as tk
import tkinter.filedialog
from pathlib import Path

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
pd.set_option('precision',10)

#select files into tuple 'datafiles' via tkinter

root = tkinter.Tk()
pathdir='/***/DSM_Exports/'

datafiles = tkinter.filedialog.askopenfilenames(parent=root,title='Choose a file', initialdir=pathdir)
datafiles = root.tk.splitlist(datafiles)

#prepare subplots template n rows, 1 column

fig = make_subplots(rows=len(datafiles), cols=1, shared_xaxes=True, vertical_spacing=0.01)

# set up loop to create subplot

for counter in range (0, len(datafiles)):  #Set up loop with length of datafiles tuple
    print(counter, datafiles[counter])

    # import file
    table=pd.read_csv(datafiles[counter], sep="\t", header=None)  

    pd.set_option('expand_frame_repr', False)

    # extract DSM cumulative dose column

    numrows = table.shape[0]+1
    print('Number of rows', numrows)

    DSMcml= table[[1,2,3]] #extract colulmns start time, end time and cumul dose
                       #double paranthesis!
    DSMcml= DSMcml.iloc[1:numrows] #cut column name

    DSMcml[2]= pd.to_datetime(DSMcml[2]) #convert to datetime endtime

    DSMcml[3]=DSMcml[3].str.replace(',','.') #change dot to comma in [3]
    DSMcml[3]=DSMcml[3].astype(float, errors = 'raise') #change [3] to float

    DSMcml= DSMcml[DSMcml[3]>=0].dropna() #>>remove lines with values <0

    fig_Xdata= DSMcml[2] #extract end times for X-axis
    fig_Ydata= DSMcml[3].round(10) #extract cumul dose for Y-axis
    
    tracename=Path(datafiles[counter]).stem

    fig.add_trace(
        go.Scatter(x=fig_Xdata, y=fig_Ydata, mode='lines', name=tracename),
        row=counter+1, col=1)
   
    fig.update_layout(title_text=datafiles[counter], hovermode='x unified', hoverlabel_namelength=-1)
    fig.update_xaxes(showspikes=True, spikecolor='green', spikesnap='cursor', spikemode='across', spikedash='solid')

counterstring=str(counter+1)   #set x-axis indicator for shared spike-line
fig.update_traces(xaxis='x'+counterstring) # set shared spike-line

fig.show()
```


Solution

You can use a hovertemplate when you add your traces:

fig.add_trace(go.Scatter(x=fig_Xdata, y=fig_Ydata, 
hovertemplate='%{y:.10f}', mode='lines', name=tracename), row=counter+1, col=1)


Answered By - Derek O
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to read in decimals with dot-seperator correctly with Excel?

 August 09, 2022     csv, decimal, excel, formatting, windows     No comments   

Issue

I am trying to read in a CSV file in Excel which contains decimals with several decimal places. My procedure:

  1. Click Data upper Tab
  2. Click From Text/CSV
  3. Choose my file that I want to read in
  4. Click Load

If I open the csv with a text editor, the file looks as follows:

Label pre-annotated,Label self-annotated,Begin pre-annotated,End pre-annotated,Begin self-annotated,End self-annotated,Difference Begin,Difference End
P,P,0,3.36998958333333,0,3.36998958333333,0,0.0
P,P,5.50998958333333,5.85998958333333,5.50998958333333,5.85998958333333,0.0,0.0
P,P,6.37998958333333,6.67998958333333,6.37998958333333,6.67998958333333,0.0,0.0
P,P,6.80998958333333,7.80998958333333,6.80998958333333,7.80998958333333,0.0,0.0
P,COND1,10.3299895833333,10.36996875,10.3299895833333,10.517009268921914,0.0,0.14704051892191394

where the decimal places start with a dot. However, after loading it into Excel the dots are not recognized and the table looks as follows:

Table loading in, numbers are not formatted correctlty

I tried changing the Excel decimal separator to dot and comma, but it did not help. Even when changing decimal separator to dot in Windows, it does not work.

Any help would be appreciated.


Solution

As comments have pointed out, this seems to be a regional issue with separators. Changing the separators in the Windows system or in Excel did not help with this problem.

The workaround that I found was adding SEP=, as the first line to my CSV file in a text editor.



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

[FIXED] how to input two decimal number

 August 09, 2022     decimal, floating-point, java     No comments   

Issue

import java.text.DecimalFormat;
import java.util.Scanner;


public class DecimalFormatExample
{
public static void main(String[] args)
{
    Scanner input=new Scanner(System.in);

    double number1;
    double number2;
    double number3;

    System.out.print("Insert first number:");
    number1=input.nextInt();

    System.out.print("Insert second number:");
    number2=input.nextInt();

    System.out.print("Insert third number:");
    number3=input.nextInt();

    DecimalFormat df = new DecimalFormat("0.00");

    System.out.println(df.format(number1));
    System.out.println(df.format(number2));
    System.out.println(df.format(number3));
}}

when i insert the first number for example:

Insert first number:1

it will print out 1.00

if i insert the number Insert first number:1.00, i get error. How can i put insert the number with decimal point?


Solution

You wrote number1=input.nextInt(); but "1.00" is not an int; it is a double. Try number1=input.nextDouble(); instead.



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

[FIXED] How to determine if a number has a decimal point, or float?

 August 09, 2022     decimal, lua     No comments   

Issue

Good afternoon. I'm constructing a binary module for a platform that uses lua for developers, and I'm accomplishing this by successive division from this video to get the remainder as an alternative, however, I am at a roadblock here to detect a decimal point.

My goal is to detect a number that has a decimal point and use successive division like the video to index into a table and loop through, for my binary module. I've tried to check if ceiling a number (that's a float) would equal rounding it + .5, this works, however, it isn't a long term solution IMO.

for _, value in pairs({4.2, 4.1, 4.9, 5}) do --> loops through a table containing numbers.
    if math.ceil(value) == math.round(value+.5) then --> checks if a number ceils and equals?
        local b = script:SetAttribute(tostring('Remainder'), value) --> prints on first 3 elements.
    else
        print('no remainder') --> prints on last element of table, '5'.
    end
end

I have also tried dividing in a loop, wasn't a good way.

I've searched up some of my problems on here, google, or lua websites, none had what I was looking for, or were simply not suitable for my codebase. So, how would I accomplish checking if a number has a decimal or a remainder?


Solution

Use modulo/remainder division(%) . What that does is it checks and gives you the remainder. For instance 20%6 would give you "2" as the answer since 20÷6 = 3 remainder 2.



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

Monday, August 8, 2022

[FIXED] How to change decimal separator in ExecuteReader c#

 August 08, 2022     .net, c#, decimal, executereader     No comments   

Issue

How to change decimal separator in string, e.g. in mnoz_obj item the returned value is 24,000 and I need to have 24.000. The values are from database to JSON. I tried ToString(new CultureInfo etc.) but this doesn't work. I expect that myString.Replace(",",".") is not correct way to do it.

public static string getDoklad()
        {
            var dbCon = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
            string[] fileArguments = Environment.GetCommandLineArgs();
            List<ZebraPolozky> zebraPolozky = new List<ZebraPolozky>();
            using (var cn = new OdbcConnection(dbCon))
            {
                OdbcCommand cmd = cn.CreateCommand();
                cmd.CommandText = "SELECT * FROM cis06zebrap";
                cn.Open();
                using (var reader = cmd.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            ZebraPolozky zebraPolozka = new ZebraPolozky
                            {
                                doklad = reader["doklad"].ToString(),
                                sklad = reader["sklad"].ToString(),
                                reg = reader["reg"].ToString(),
                                mnoz_obj = reader["mnoz_obj"].ToString(),
                                mnoz_vyd = reader["mnoz_vyd"].ToString(),
                                kc_pce = reader["kc_pce"].ToString(),
                                sarze = reader["sarze"].ToString(),
                                datspo = reader["datspo"].ToString(),
                                veb = reader["veb"].ToString(),
                                poc2 = reader["poc2"].ToString(),
                                pvp06pk = reader["pvp06pk"].ToString(),
                                znacky = reader["znacky"].ToString(),
                                stav = reader["stav"].ToString(),
                                //prac = reader["prac"].ToString(),
                                //exp = reader["exp"].ToString()
                            };
                            zebraPolozky.Add(zebraPolozka);
                        }
                    }
                }
                cn.Close();
            }
            //var collw = new { polozky = zebraPolozky };
            var jsonString = JsonConvert.SerializeObject(zebraPolozky);
            return jsonString;
        }

{
    "doklad": "568375",
    "sklad": "901",
    "reg": "185121",
    "mnoz_obj": "24,000",
    "mnoz_vyd": "0,000",
    "kc_pce": "240,72",
    "sarze": "",
    "datspo": "",
    "veb": "24,00",
    "poc2": "1",
    "pvp06pk": "116783437",
    "znacky": "R1902",
    "stav": "0"
  }

Solution

OdbcDataReader gives the value in its native format as stated in the doc.

You should then be able to cast it and use the overload of .ToString() you need.

Try something like:

((decimal)reader["mnoz_obj"]).ToString("N2")


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

[FIXED] how to divide two intengers and get a result with decimal numbers?

 August 08, 2022     c, contiki, decimal, floating-point, integer     No comments   

Issue

I'm doing a project in Contiki to a Zolertia module where I need to calculate the risk of a wildfire to occur.

To calculate this risk the formula used is Risk = Temperature / Humidity.
The result of Risk it's a decimal value and there are 5 different values range to classify this Risk: 0-0.49 , 0.5-0.99, 1-1.49, 1.5-1.99, >=2.

My problem is that I can't get decimal results. When I run it in the terminal it shows the value of Temperature and the value of Humidity but just a blank space in the value of Risk.

My code is:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "contiki.h"
#include <float.h>

PROCESS(temp_hum_fog, "Wildfire Control");
AUTOSTART_PROCESSES(&temp_hum_fog);

static struct etimer et;

PROCESS_THREAD(temp_hum_fog, ev, data)
{
    
    int16_t temp, hum;
    float risk;

    PROCESS_BEGIN()


    while(1) {
        etimer_set(&et, CLOCK_SECOND);
        PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

        temp = rand() % 45;
        hum = rand() % (85-5)+5;
        risk = (float)temp/(float)hum;

        printf("Temperature:%d ºC\nHumidity:%d HR\nRisk:%f\n", temp,hum,risk);

    }

    PROCESS_END();


}

If I change the type of temp and hum to float it won't show any results also so I'm not sure if float works in Contiki.

Does someone know any solution?


Solution

The C implementation you are using is not a full standard C implementation and does not support floating-point conversions in printf. Three options are:

  • Check the documentation for your C implementation to see if support for floating-point can be enabled.
  • Find another C implementation to use (particularly the standard C library).
  • Use integer arithmetic, as in the example below, to do calculations.

This code will print the quotient to two decimal places, rounded down, using only integer arithmetic:

    int integer  = temp/hum;
    int fraction = temp%hum * 100 / hum;
    printf("Risk: %d.%02d\n", integer, fraction);

Note this assumes the values involved are positive; negative numbers could cause undesired outputs.



Answered By - Eric Postpischil
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] why does the number 51444.325061 doesnot round off to 51444.325 upto 3 decimal places? I want to round off this number in c programming

 August 08, 2022     c, decimal, floating-point, precision, rounding     No comments   

Issue

#include <stdio.h>
#include <stdlib.h>

int main() {
    float n;
    scanf("%f", &n);
    printf("%.3f", n);
}

input: 51444.325061

my output: 51444.324

expected output: 51444.325

why does I dont get the proper answer?


Solution

32-bit float can encode about 232 different values.

51444.325061is not one of them**. Instead the nearest float is exactly 51444.32421875. The next best choice would be 51444.328125.

Printing 51444.32421875 to 3 decimal places is best as "51444.324".


why does I dont get the proper answer?

float is too imprecise to encode 51444.325061 as OP desires. Using double will help. The same problem exists, yet only appears when about 16+ significant digits are needed.


** Encodable finite values are of the form: some_integer * 2some_exponent.



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

[FIXED] How would I use js to convert a decimal to number to a hex string?

 August 08, 2022     decimal, hex, javascript     No comments   

Issue

Decimal input: 76561198291043943
Hex output: 110000113b74660
Hex expected output: 110000113b74667

For some reason, when I use the following snippet and execute it, the expected result does not occur, but when I use https://www.binaryhexconverter.com/decimal-to-hex-converter to convert a decimal number to a hex string, I get the expected output.

console.log(Number(76561198291043943).toString(16))


Solution

76561198291043943 is greater than Number.MAX_SAFE_INTEGER.

Use BigInt instead:

console.log(BigInt("76561198291043943").toString(16))



Answered By - Spectric
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to cast nulls to blank and those with number to decimal 3 places?

 August 08, 2022     decimal, sql-server, varchar     No comments   

Issue

If I want the output to be blank if there is no gpa, and rounded to 3 decimal places if there is a gpa - how do I get that in one statement?

Here are the 2 statements I have come up with that I am having trouble combining as one (for blank if answer is null and 3 places decimal if there is a gpa).

decimal 3 places:

NULLIF(cast(round(termgpa.gpa, 3) AS DECIMAL(18, 3)), 0)

if null then blank:

isnull(cast(termgpa.gpa as varchar), ' ')

Solution

How about using a case statement. Also, if you want the column to contain both blanks and decimal numbers you will have to cast it as a varchar. The below statement shows both null and non null.

declare @gpa decimal(18,5)

set @gpa = '5.789456'
select 
    case
        when @gpa is null then ''
        else cast(cast(round(@gpa, 3) AS DECIMAL(18, 3)) as varchar)
    end as gpa
--returns 5.789

set @gpa = null
select 
    case
        when @gpa is null then ''
        else cast(cast(round(@gpa, 3) AS DECIMAL(18, 3)) as varchar)
    end as gpa
--returns blank


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

[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

[FIXED] Why do I get a decimal error when I substract two numbers with Excel VBA?

 August 08, 2022     decimal, excel, vba     No comments   

Issue

I have made a simplified example that shows my issue. When substracting one number from another I get a false result. I could round the result with 2 decimals, but this is more a workaround.

Sub Test()
    Dim Sale As Double
    Dim Fee As Double
    Dim Payment As Double
    Payment = 104953.98
    Sale = 105000
    Fee = Sale - Payment
End Sub

Testing the code in the immediate window shows that Fee is calculated to 46,0200000000041 which is false.


Solution

Based on the naming of the variables you might want to try this

Sub Test()
    Dim Sale As Currency
    Dim Fee As Currency
    Dim Payment As Currency
    Payment = 104953.98
    Sale = 105000
    Fee = Sale - Payment
End Sub

You also should read on Floating-point arithmetic and https://floating-point-gui.de/



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

[FIXED] Why does an "YYYY.MM" date converted with df['date'].astype(str).str[-2:] come out between 0 and 1?

 August 08, 2022     dataframe, decimal, pandas, python     No comments   

Issue

I have the following dataframe:

date    sea_temp_diff   wind_distance_diff  wind_speed_diff temp_diff   humidity_diff   current_distance_diff   current_speed_diff  month   year
0   2017.04 2.600000    20.000000   -4.000000   0.000000    0.000000    -90.000000  -1.000000e-01   04  2017
1   2017.05 -1.553333   8.666667    0.833333    -0.766667   0.000000    95.000000   -1.300000e-01   05  2017
2   2017.06 -1.551852   -10.370370  -1.888889   -0.888889   0.000000    179.629630  -2.851852e-01   06  2017
3   2017.07 -1.653571   -20.000000  -2.357143   -1.071429   0.000000    77.142857   -3.000000e-01   07  2017
4   2017.08 -1.287500   -8.333333   -1.916667   -1.166667   0.000000    88.333333   -2.041667e-01   08  2017
5   2017.09 -1.262500   3.333333    -1.375000   0.166667    615.833333  13.333333   -3.750000e-02   09  2017
6   2017.10 -0.809677   -146.451613 -161.548387 0.419355    -7.064516   -79.354839  -1.613645e+02   .1  2017

I generated this dataframe with:

australia_overview_clean['month'] = australia_overview_clean['date'].astype(str).str[-2:]
australia_overview_clean

For some reason though, instead of returning the '10' month, I get '0.1'. while it is mathematically identical to 10 or 0.10, I wouldn't mind finding a way to put 10 in its place instead. Is there a way I can fix this?


Solution

You can get your year and month from the date by splitting on ".". ljust is used to make sure the date column is 7 characters long before splitting.

df[["year", "month"]] = df["date"].astype(str).str.ljust(7,"0").str.split(".", expand=True).astype(int)

>>> df[["date", "year", "month"]]
      date  year  month
0  2017.04  2017      4
1  2017.05  2017      5
2  2017.06  2017      6
3  2017.07  2017      7
4  2017.08  2017      8
5  2017.09  2017      9
6  2017.10  2017     10


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

[FIXED] How do i store a binary number in an array?

 August 08, 2022     arrays, binary, c++, decimal, random     No comments   

Issue

Ok, so i been working on this right here that is intended to be part of a encryption software that works synonymously like 2fa

 #include <iostream>
 #include <cstdio>     
 #include <cstdlib>   
 #include <ctime>    
 using namespace std;

 int main()
 {


int RGX;
int box[32];

srand (time(NULL));


RGX = rand() % 100000000 + 9999999;

cout << "Random Generated One Time HEX #:" << endl;

cout << std::hex << RGX << endl;


while(RGX!=1 || 0)
{

int m = RGX % 2;
cout << " " << m << " ";


RGX = RGX / 2;


cout << RGX << endl;



} 

return 0;
}

Here is a sample of what it outputs:

Random Generated One Time HEX #:
3ff3c70
0 1ff9e38
0 ffcf1c
0 7fe78e
0 3ff3c7
1 1ff9e3
1 ffcf1
1 7fe78
0 3ff3c
0 1ff9e
0 ffcf
1 7fe7
1 3ff3
1 1ff9
1 ffc
0 7fe
0 3ff
1 1ff
1 ff
1 7f
1 3f
1 1f
1 f
1 7
1 3
1 1


** Process exited - Return Code: 0 **

The result is different each time since it's randomized, i'm still not finished. But what i need to know is how do i store the binary value in an array, the binary value are the numbers on the left.


Solution

You can use a std::bitset instead of manually extracting bits and the array:

#include <iostream>
#include <ctime> 
#include <cstdlib>   
#include <bitset>

int main() {
    srand (time(NULL));
    int RGX = rand() % 100000000 + 9999999;

    std::cout << "Random Generated One Time HEX #: \n";
    std::cout << std::hex << RGX << "\n";
    std::bitset<32> box(RGX);
    for (int i=0;i<32;++i){
        std::cout << box[i];
    }
 
}

Possible output:

Random Generated One Time HEX #: 
478ada7
11100101101101010001111000100000

No inside the brackets after " while(RGX!=1 || 0) " it uses % and divides by 2 up until it gets to 1 or 0.

No. Thats not what that condition says. The condition says "loop while (RGX is not equal to 1) or 0". As 0 is always false when converted to bool, your condition is equivalent to while(RGX != 1).



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

Sunday, August 7, 2022

[FIXED] How do I force a python Decimal to have atleast two decimals?

 August 07, 2022     decimal, python     No comments   

Issue

I would need to format a python Decimal object to have atleast two decimals, but no more than 5. Is there a reliable way to do this? Examples:

1.6 --> 1.60
1.678 --> 1.678
1.98765 --> 1.98765

If there are more than two decimals, it is vital that it does not get truncated to only two decimals.


Solution

It looks to me like there are two parts to this question - one, determining the correct number of digits and two, quantizing the values to that number of digits.

To do the first, I would get the current exponent using the as_tuple() method. Unless I'm overlooking something simpler.

>>> import decimal
>>> d = decimal.Decimal("1.678")
>>> d.as_tuple().exponent
-3

>>> d2 = decimal.Decimal("1.6")
>>> d2.as_tuple().exponent
-1

So from that you can compute the desired exponent:

MAX_EXPONENT = -2
MIN_EXPONENT = -5
def desired_exponent(d):
    current_exponent = d.as_tuple().exponent
    return min(MAX_EXPONENT, max(MIN_EXPONENT, current_exponent))

The second is answered by the accepted answer on the marked duplicate - use the quantize() method. You'll need to construct a Decimal value with the desired exponent you can provide as the argument to quantize(). There are multiple ways to do that, but two simple ones are exponentiating decimal.Decimal("10") or using the tuple constructor for decimal.Decimal().

>>> quant_arg = decimal.Decimal("10") ** -2
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')

Or:

>>> quant_arg = decimal.Decimal((0, (), -2))
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')

I used -2 as a literal there, you'd want to use the calculated value of desired_exponent.

There are multiple ways to organize this code, I think the parts that are not obvious are a) accessing the current exponent of a decimal value and b) some of the ways of constructing an arg for quantize(). And this is all assuming you need the actual decimal objects, and aren't just outputting them - if this is a question just about output formatting re-quantizing is probably overkill.



Answered By - Peter DeGlopper
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

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